while and do-while Loops
Loops repeat code. A while loop keeps going as long as its condition is true — the right choice when you don't know in advance how many times you'll repeat: reading input until it ends, retrying, or iterating until a value converges.
while
#include <stdio.h> int main(void) { int countdown = 3; while (countdown > 0) { printf("%d...\n", countdown); countdown--; } printf("Lift off!\n"); return 0; }
3... 2... 1... Lift off!
The condition is checked before each pass. If it's false at the start, the body never runs. Something in the body must eventually make it false, or the loop runs forever — press Ctrl+C to stop a runaway program.
An unknown number of steps
#include <stdio.h> int main(void) { double balance = 1000.0; int years = 0; while (balance < 2000.0) { balance *= 1.05; years++; } printf("Doubled after %d years: %.2f\n", years, balance); return 0; }
Doubled after 15 years: 2078.93
Working through digits
Repeatedly dividing by 10 peels off the last digit — a pattern you'll see often:
#include <stdio.h> int main(void) { unsigned long n = 9075123; int digits = 0, sum = 0; unsigned long reversed = 0; while (n > 0) { int last = n % 10; sum += last; reversed = reversed * 10 + last; digits++; n /= 10; } printf("%d digits, sum %d, reversed %lu\n", digits, sum, reversed); return 0; }
7 digits, sum 27, reversed 3215709
do-while
A do…while loop checks its condition after the body, so the body always runs at least once — natural for "ask, then decide whether to ask again":
#include <stdio.h> int main(void) { char line[32]; int choice = 0; do { printf("Pick 1-3: "); if (fgets(line, sizeof line, stdin) == NULL) { return 1; } if (sscanf(line, "%d", &choice) != 1) { choice = 0; } } while (choice < 1 || choice > 3); printf("\nYou picked %d.\n", choice); return 0; }
7 two 2
Pick 1-3: Pick 1-3: Pick 1-3: You picked 2.
Note the semicolon after while (…) at the end of a do loop.
Infinite loops on purpose
Servers, games and menus often loop "forever" and leave with break or return. while (1) and for (;;) are the two usual spellings:
#include <stdio.h> int main(void) { unsigned n = 27; int steps = 0; while (1) { if (n == 1) { break; } n = (n % 2 == 0) ? n / 2 : 3 * n + 1; steps++; } printf("Reached 1 after %d steps\n", steps); return 0; }
Reached 1 after 111 steps
Common mistakes
- A stray semicolon:
while (x < 10);makes an empty loop body that never changesx— an infinite loop. Compilers warn about this with-Wempty-body. - Off-by-one:
<versus<=decides whether the last value is included. Trace the first and last iteration by hand. - Forgetting to update the variable the condition depends on.
Try it yourself
Find the greatest common divisor of two numbers with Euclid's algorithm: replace (a, b) with (b, a % b) until b is zero.
gcd(1071, 462) = 21