While Loops: Repeat While a Condition Holds
Keep going until the limit
A while loop uses the same test-before-work idea as for, but its header contains only the condition. Here the setup comes before the loop and the update goes inside its body. The program labels spaces 1 through 3.
#include <stdio.h>
int main(void) {
int space = 1;
while (space <= 3) {
printf("Space %d\n", space);
space = space + 1;
}
printf("Done\n");
return 0;
}
The setup sets space to 1 before the loop. Each successful check runs the braced body: print the current value, then add one. The checks see 1, 2, 3, and finally 4. Four fails space <= 3, so the program leaves the loop and prints Done.
If space started at 4, the very first check would fail. The body would run zero times, but Done would still print. A while does not promise a first pass.
The update need not add one
#include <stdio.h>
int main(void) {
int width = 2;
while (width < 10) {
printf("Width: %d\n", width);
width = width * 2;
}
printf("Width limit reached\n");
return 0;
}
This time the update doubles width. The program tests 2, 4, 8, then 16; only the first three values print because 16 fails < 10.
Run both examples. For each, point to the initial value, the condition, and the update that eventually makes the condition false. A missing update can leave a loop running forever. In the countdown exercise, you'll move toward zero by subtracting instead.