C While Loop
A loop repeats a block of code. Loops save you from writing the same statement over and over, and they let a program keep working until some condition changes — reading until the end of a file, retrying until a connection succeeds, counting until a goal is reached.
C has three loops: while, do…while and for. This lesson covers the first two.
The while loop
while (condition) {
// body: repeated as long as condition is true
}The condition is checked before every pass through the body. If it is true (non-zero) the body runs, and then the condition is checked again. As soon as it is false, the loop ends and the program continues after the closing brace.
#include <stdio.h>
int main(void) {
int i = 1;
while (i <= 5) {
printf("Pass number %d\n", i);
i++;
}
printf("Loop finished, i is now %d\n", i);
return 0;
}Pass number 1
Pass number 2
Pass number 3
Pass number 4
Pass number 5
Loop finished, i is now 6
Every while loop that counts has three ingredients: a variable set before the loop (i = 1), a condition (i <= 5) and an update inside the body (i++).
Watch out: If you forget the update, the condition never becomes false and the loop runs forever — an infinite loop. In a terminal you can stop such a program with Ctrl+C.
When you don't know the number of repetitions
while is the natural choice when the loop should continue until something happens, rather than a fixed number of times. How many times must you halve 1000 before it drops below 1?
#include <stdio.h>
int main(void) {
double value = 1000;
int steps = 0;
while (value >= 1) {
value = value / 2;
steps++;
}
printf("After %d halvings the value is %.4f\n", steps, value);
return 0;
}After 10 halvings the value is 0.9766
Another classic: taking a number apart digit by digit. n % 10 gives the last digit, and n / 10 removes it.
#include <stdio.h>
int main(void) {
int n = 90417;
int digit_sum = 0;
int digits = 0;
while (n > 0) {
digit_sum += n % 10;
n /= 10;
digits++;
}
printf("digits: %d, digit sum: %d\n", digits, digit_sum);
return 0;
}digits: 5, digit sum: 21
The do…while loop
A do…while loop checks its condition after the body. That guarantees the body runs at least once, even if the condition is false from the start.
do {
// body
} while (condition); // note the semicolon!#include <stdio.h>
int main(void) {
int countdown = 3;
do {
printf("%d... ", countdown);
countdown--;
} while (countdown > 0);
printf("Liftoff!\n");
int x = 100;
do {
printf("Runs once although x < 10 is false: x=%d\n", x);
} while (x < 10);
return 0;
}3... 2... 1... Liftoff!
Runs once although x < 10 is false: x=100
do…while is ideal for menus and input validation: show the menu, read a choice, and repeat while the choice is invalid. You always need to show the menu at least once.
while vs. do…while
while |
do…while |
|
|---|---|---|
| Condition checked | before each pass | after each pass |
| Minimum number of runs | 0 | 1 |
Ends with ; |
no | yes, after while (…) |
| Typical use | loop until a state changes | menus, "try, then check" logic |
Tracing a loop
When a loop surprises you, trace it on paper with a small table. For int i = 10; while (i > 0) { i -= 3; }:
| Check | i before |
Condition | i after body |
|---|---|---|---|
| 1 | 10 | true | 7 |
| 2 | 7 | true | 4 |
| 3 | 4 | true | 1 |
| 4 | 1 | true | -2 |
| 5 | -2 | false | — (loop ends) |
Tip: Adding a temporary
printfinside the loop that prints the loop variable is the quickest way to see what is going on.
Test yourself
How many times does the body of int i = 0; while (i < 3) { i++; } run?
- 2
- 3
- 4
- Forever
What is the key difference of a do…while loop?
- It is faster
- Its body always runs at least once
- It cannot use break
- It needs a counter variable
What happens with int n = 5; while (n > 0) { printf("%d", n); }?
- Prints 54321
- Prints 5 once
- Runs forever printing 5
- Does not compile