Loops
To do the same thing many times, you don't copy the code many times: you write a loop. Loops are where Step is most worth pressing: you can watch the program go around and around, and see the variables change each time.
1#include <stdio.h>2 3int main(void) {4 int n = 3;5 while (n > 0) {6 printf("%d\n", n);7 n--;8 }9 printf("Go!\n");10 return 0;11}
3 2 1 Go!
The while loop
while checks the condition in its parentheses. If it holds, the loop body runs once and the program goes back to check the condition again. If it doesn't, the body is skipped and the program carries on below.
A loop that stops usually has three things:
| Part | In the example above |
|---|---|
| Before the loop, give a variable a value | int n = 3; |
| A condition checked before each round | n > 0 |
| Something in the body that changes the variable | n--; |
1#include <stdio.h>2 3int main(void) {4 int day = 1;5 while (day <= 5) {6 printf("Day %d\n", day);7 day++;8 }9 printf("When the loop ends, day is %d\n", day);10 return 0;11}
Day 1 Day 2 Day 3 Day 4 Day 5 When the loop ends, day is 6
Look at the last line: when the loop stops, day is already 6, the first value for which day <= 5 does not hold.
How many lines does this print?
1#include <stdio.h>2 3int main(void) {4 int n = 1;5 while (n < 10) {6 printf("%d\n", n);7 n = n * 2;8 }9 return 0;10}
n goes 1, 2, 4, 8, all below 10, and each prints a line. On the next round n becomes 16, the condition fails, and the loop stops. Four lines in all.
Adding up as you go
One of the most common jobs for a loop is adding up many numbers. Start a variable at 0 and add one number to it each time around:
1#include <stdio.h>2 3int main(void) {4 int total = 0;5 int i = 1;6 while (i <= 10) {7 total += i;8 i++;9 }10 printf("The sum of 1 to 10 is %d\n", total);11 return 0;12}
The sum of 1 to 10 is 55
Press Step and keep an eye on total: 0, 1, 3, 6, 10... each round adds one more i.
Counting how many
Counting works the same way: start a variable at 0 and add 1 whenever something matches. Here we count the multiples of 3 from 1 to 30:
1#include <stdio.h>2 3int main(void) {4 int count = 0;5 int i = 1;6 while (i <= 30) {7 if (i % 3 == 0) {8 count++;9 }10 i++;11 }12 printf("There are %d\n", count);13 return 0;14}
There are 10
Sometimes you don't know how many rounds it takes, only when to stop. Say you save $300 a month: how many months until you have $2000?
1#include <stdio.h>2 3int main(void) {4 int balance = 0;5 int months = 0;6 while (balance < 2000) {7 balance += 300;8 months++;9 }10 printf("After %d months you have $%d\n", months, balance);11 return 0;12}
After 7 months you have $2100
The for loop
Loops that count "from here to there" are so common that C has a more compact way to write them: for. It puts the start, the condition and the change on one line, separated by semicolons:
1#include <stdio.h>2 3int main(void) {4 for (int i = 1; i <= 5; i++) {5 printf("Round %d\n", i);6 }7 printf("All done\n");8 return 0;9}
Round 1 Round 2 Round 3 Round 4 Round 5 All done
| Part | When it runs |
|---|---|
int i = 1 | once, at the very start |
i <= 5 | before each round; when it fails, the loop ends |
i++ | after the body, each round |
This i is declared inside the for, so it exists only in this loop; when the loop ends, it is gone.
The third part doesn't have to be i++. It can go up by 10, or count down:
1#include <stdio.h>2 3int main(void) {4 for (int c = 0; c <= 40; c += 10) {5 printf("%d Celsius = %d Fahrenheit\n", c, c * 9 / 5 + 32);6 }7 for (int i = 10; i > 0; i -= 3) {8 printf("%d\n", i);9 }10 return 0;11}
0 Celsius = 32 Fahrenheit 10 Celsius = 50 Fahrenheit 20 Celsius = 68 Fahrenheit 30 Celsius = 86 Fahrenheit 40 Celsius = 104 Fahrenheit 10 7 4 1
Tip: When you know how many rounds, use for. When you only know when to stop (until you've saved enough, say), use while. Either can do the job; pick the one that reads more clearly.
do while: act first, ask later
while checks the condition first, so if it fails from the start, the body never runs. do while turns that around: it runs the body first and checks afterwards, so the body runs at least once. Note the semicolon after the final while (...).
1#include <stdio.h>2 3int main(void) {4 int n = 10;5 while (n < 5) {6 printf("while ran\n");7 }8 do {9 printf("do while ran\n");10 } while (n < 5);11 return 0;12}
do while ran
Both loops have the same condition, and n < 5 fails for both. The while body never ran; the do while body ran once, and only then found out it should stop.
Infinite loops
If the condition always holds, the loop never stops. This is an infinite loop. The most common cause is forgetting to change the variable:
1int n = 3;2while (n > 0) {3 printf("%d\n", n);4}
There is no n-- in the body, so n stays 3, n > 0 always holds, and the program prints 3 forever. In a terminal, the only way out is to stop it with Ctrl+C. On this page, a program that takes too many steps without finishing is stopped for you, with a message saying so.
When a program won't stop, check three things: Is the condition right? Does the body change the variable? Does it change in the right direction (subtracting where you meant to add never gets there)?
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Multiply 1 to 5
✓Use a loop to work out 1 × 2 × 3 × 4 × 5, and print the result 120.
120
1#include <stdio.h>2 3int main(void) {4 int product = 1;5 6 return 0;7}
Price list
✓A coffee costs $3. Use a for loop to print the price of 1 to 4 coffees, one per line, exactly as below.
Cups: 1, total: $3 Cups: 2, total: $6 Cups: 3, total: $9 Cups: 4, total: $12
1#include <stdio.h>2 3int main(void) {4 int price = 3;5 6 return 0;7}
Ten thousand steps
✓One lap of the track is 450 steps for Ana. Use while to find the fewest laps she needs to reach 10000 steps, and print 23 laps, 10350 steps.
23 laps, 10350 steps
1#include <stdio.h>2 3int main(void) {4 int steps = 0;5 int laps = 0;6 7 return 0;8}
What you learned
whilechecks the condition, runs the body if it holds, then checks again; if it fails from the start, the body never runs.for (start; condition; change)puts all three on one line, which suits counting "from here to there".do whileruns first and checks afterwards, so the body runs at least once; it ends with a semicolon.- Adding up and counting: start a variable at 0 and add to it each round.
- A condition that always holds makes an infinite loop; check the condition, and check that the body changes the variable in the right direction.