The do-while Loop
The while loop checks its condition before each iteration. If the condition is false right at the start, the block doesn't run even once. Usually, that's exactly what you want. But sometimes the block has to run at least once. For that, C has the do ... while loop, which checks the condition after each iteration:
int count = 1;
do {
printf("%d\n", count);
count++;
} while (count <= 3);1
2
3The keyword do comes first, then the block, and the condition comes at the end, after the closing brace. The program runs the block, then checks the condition, and if it's true, it runs the block again. Note the semicolon after the condition: } while (count <= 3);. Without it, the compiler reports error: expected ';' after do/while statement.
The difference shows when the condition is false from the start:
int count = 10;
do {
printf("%d\n", count);
count++;
} while (count <= 3);10The block runs once and prints 10, and only then does the loop find out that 11 <= 3 is false. A while loop with the same condition wouldn't print anything.
When is that useful? Say you want to count the digits of a number. Integer division by 10 drops the last digit (2026 / 10 is 202), so you can divide until nothing is left: 2026, 202, 20, 2, 0. That's four divisions, so the number has four digits:
int number = 2026;
int digits = 0;
do {
digits++;
number /= 10;
} while (number > 0);
printf("Digits: %d\n", digits);Digits: 4A while loop would work for 2026 too. But the number 0 is also written with one digit, and for 0, while (number > 0) wouldn't run at all, so the program would say it has 0 digits. do ... while runs the block at least once, so 0 gets its one digit.
In practice, do ... while is used much less often than while and for. In programs on your own computer, it is handy when a program asks the user for something and asks again while the answer is wrong. The programs on this site get their data from variables, so you won't need it often.
Instructions
The program in the editor counts the digits of number. Run it: it prints Digits: 0, but 0 is written with one digit. Rewrite the while loop as a do ... while loop: do before the block, and while (number > 0); after its closing brace. Then the program prints Digits: 1.
Check that the loop still works for other numbers: change the value of number to 2026. The program prints Digits: 4.
Start programming for free
10/11