C While Loop
Loops let you run the same block of code again and again without copying it. The while loop is the simplest loop in C: it keeps repeating as long as a condition stays true.
The while Loop
A while loop checks a condition before every pass. As long as the condition evaluates to true (any non-zero value), the code inside the curly braces runs. When the condition becomes false, the loop stops and the program continues after the loop.
Counting from 0 to 4
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("i is %d\n", i);
i++;
}
return 0;
}In the example above, i starts at 0. The condition i < 5 is checked each time. We print the value, then i++ increases i by 1. After i reaches 5 the condition is false, so the loop ends. The output is the numbers 0, 1, 2, 3, and 4 each on their own line.
- The condition is tested first, before the body runs.
- If the condition is false at the start, the body never runs at all.
- Use a counter variable to control how many times the loop repeats.
Summing numbers with a while loop
#include <stdio.h>
int main() {
int number = 1;
int sum = 0;
while (number <= 5) {
sum += number;
number++;
}
printf("The sum is %d\n", sum);
return 0;
}Here we add 1 + 2 + 3 + 4 + 5 by looping while number is 5 or less. Each pass adds number to sum, then increases number. The program prints: The sum is 15.
Exercise: C While Loop
If a while loop's condition is false the very first time it is checked, how many times does the body run?