← The C Language Lesson 16 of 77 · 10 XP

The while loop

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

while (condition) {
    ...      // repeats as long as the condition is true (not 0)
}

There's also a version that checks after the body — do … while. It runs at least once:

int n;
do {
    printf("Enter a positive number: ");
    scanf("%d", &n);
} while (n <= 0);

A classic K&R idiom is to read input as long as there is some:

int x;
while (scanf("%d", &x) == 1) {
    ...      // scanf returns something other than 1 when the input ends or isn't a number
}

Task. Read a non-negative whole number and print how many digits it has. The number 0 has one digit.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.