The while Loop
Imagine you need to print the numbers from 1 to 100. You could write printf a hundred times, but it would take ages, and changing anything later would be even worse. Programs repeat work like this all the time: they go through every student in a class, check every product in a shop, or redraw a game screen 60 times a second. That is what loops are for. A loop is a piece of code that runs again and again.
The simplest loop is while. It repeats a block of code while its condition is true:
int number = 1;
while (number <= 5) {
printf("%d\n", number);
number++;
}This prints:
1
2
3
4
5A while loop looks like an if: the keyword, a condition in parentheses and a block of code in curly braces. The difference is that if runs its block at most once, but while keeps coming back to the condition. Step by step:
- The program creates
numberwith the value1. - It checks the condition
number <= 5. It is true, so the program runs the block: it prints1, andnumber++increasesnumberto2. - It goes back to the condition.
2 <= 5is still true, so it prints2and increasesnumberto3. - And so on, until
numberis6. Then the condition is false, the loop ends, and the program continues with the code after the loop's closing brace}.
Each run of the block is called an iteration. This loop has five iterations. To print the numbers up to 100, you would only change 5 to 100.
Indent the block of a loop by 4 spaces, just like the block of an if. Then you can see at a glance what repeats. The code after the loop runs only once, when the loop has finished:
int number = 1;
while (number <= 3) {
printf("%d\n", number);
number++;
}
printf("Done\n");1
2
3
DoneNotice the line number++. Something in the block must change the variable in the condition, so that the condition becomes false at some point. Without it, the loop would never end. You'll see what happens then in the next exercise.
Instructions
Delete the three lines that print 1, 2 and 3. In their place, create a variable number of type int with the value 10. The loop will count with it.
Below it, write a while loop that runs while number is less than or equal to 20. Inside the loop, print number on its own line and then increase it by 1. The program prints the numbers from 10 to 20, each on its own line.
After the loop, below its closing brace }, print After the loop: and the value of number. The last line of the output is After the loop: 21. The variable ends up as 21, not 20, because the loop stops only when the condition is false.
Start programming for free
1/11