Kodewick
Lesson 6 of 30Contents

Loops

Lesson 6 of 30 · Part 1 · Getting started · about 15 minutes

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.

main.c
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}
Output
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:

PartIn the example above
Before the loop, give a variable a valueint n = 3;
A condition checked before each roundn > 0
Something in the body that changes the variablen--;
main.c
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}
Output
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.

Guess first

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}

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:

main.c
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}
Output
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:

main.c
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}
Output
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?

main.c
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}
Output
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:

main.c
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}
Output
Round 1
Round 2
Round 3
Round 4
Round 5
All done
PartWhen it runs
int i = 1once, at the very start
i <= 5before 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:

main.c
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}
Output
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 (...).

main.c
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}
Output
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.

Exercise 1

Multiply 1 to 5

Use a loop to work out 1 × 2 × 3 × 4 × 5, and print the result 120.

It should print
120
exercise1.c
1#include <stdio.h>2 3int main(void) {4    int product = 1;5 6    return 0;7}
Output
Press Run or Ctrl+Enter
Exercise 2

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.

It should print
Cups: 1, total: $3
Cups: 2, total: $6
Cups: 3, total: $9
Cups: 4, total: $12
exercise2.c
1#include <stdio.h>2 3int main(void) {4    int price = 3;5 6    return 0;7}
Output
Press Run or Ctrl+Enter
Exercise 3

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.

It should print
23 laps, 10350 steps
exercise3.c
1#include <stdio.h>2 3int main(void) {4    int steps = 0;5    int laps = 0;6 7    return 0;8}
Output
Press Run or Ctrl+Enter

What you learned

  • while checks 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 while runs 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.