LearnFrenzy
Sign in Take a free test

C Loops · Predict the Output · Question 7

Counting the digits of 0: while vs do-while Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following C program?

main.c
#include <stdio.h>

int main(void) {
    int n = 0, a = 0, b = 0;
    int t = n;
    while (t > 0) {
        t /= 10;
        a++;
    }
    t = n;
    do {
        t /= 10;
        b++;
    } while (t > 0);
    printf("%d %d\n", a, b);
    return 0;
}
  • A 0 1 Correct
  • B 1 1
  • C 0 0
  • D 1 0
Correct Answer: Option A

For n = 0 the while body never runs, so it claims 0 digits. The do-while counts once before testing, giving the correct answer: 0 has 1 digit.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links