C While Loop
A while loop repeats its block while a check stays true. Without it, repeating a task means writing the same lines again and again.
Count to three
Count takes the values 1, 2, then 3. The check fails at 4, so the loop stops after printing 1, 2, 3.
#include <stdio.h>
int main() {
int count = 1;
while (count < 4) {
printf("%d\n", count);
count++;
}
return 0;
}Loop that never runs
Count starts at 10, so the check is false before the first round. The block never runs, and only Done prints.
#include <stdio.h>
int main() {
int count = 10;
while (count < 4) {
printf("%d\n", count);
count++;
}
printf("Done.\n");
return 0;
}Add numbers in a loop
Each round adds the next number to total: 1, then 2, then 3. The print line shows 6.
#include <stdio.h>
int main() {
int total = 0;
int n = 1;
while (n < 4) {
total = total + n;
n++;
}
printf("%d\n", total);
return 0;
}Example
#include <stdio.h>
int main() {
int count = 5;
while (count > 0) {
printf("%d\n", count);
count--;
}
printf("Go!\n");
return 0;
}Key points
- A while loop starts with the word while and a check in round brackets.
- The code to repeat sits inside curly braces after the check.
- The check runs before each round, and the loop stops when the check is false.
- The loop needs a variable that changes inside the block, or it never stops.
- Add 1 to the counter in each round to move toward the end.
- A while loop may run zero times when the check starts false.
Count starts at 5 and falls by 1 each round. The loop stops at 0, and the last line prints Go!
Note
A check that stays true forever makes a loop that never ends, so watch the counter.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Count starts at 1. The loop runs while count is smaller than 4, and count grows by 1 each round. How many times does the block run?