Skip to content

Count with Loops

The Course
•
30 min study

A week of study is seven days, and adding seven variables by hand is tedious; a month of thirty is worse. Repetition is what computers are for. A loop runs the same block again and again while a condition holds, so one total += 20; statement can count any number of days. The price is that you must reason about exactly how many times the body runs and exactly when the loop stops. Most loop bugs are off by one: one iteration too many or one too few.

Predict and run

Before running, write a small table with one row per iteration: the value of session, then the value of total after the body.

Predict before running C
#include <stdio.h>

int main(void) {
    int total = 0;
    for (int session = 1; session <= 3; session++) {
        total += 10;
        printf("%d: %d\n", session, total);
    }
    return 0;
}
Check your prediction
Text
1: 10
2: 20
3: 30

When session reached 4, the condition failed, because 4 is not at most 3, so the body did not run a fourth time and the loop ended. Change the condition to session < 3 and count the lines: there are two, because 3 no longer passes the test.

Trace before you guess

When a loop surprises you, trace it. Write one row for every check of the condition: the counter, whether the condition holds, and each variable after the body. For the program above:

  • session 1, condition true, total becomes 10.
  • session 2, condition true, total becomes 20.
  • session 3, condition true, total becomes 30.
  • session 4, condition false, the loop ends and total stays 30.

There are four checks but only three iterations. The last row, where the condition fails, is the one people forget, and it is where off-by-one bugs hide.

The four parts of a for loop

for (init; condition; update) { body } runs in a fixed order:

  1. init runs once, before anything else. int session = 1 creates the counter.
  2. condition is checked before every iteration, including the first. If it is false, the loop ends immediately.
  3. The body runs.
  4. update runs after the body. session++ adds one to session. Then go back to step 2.

A loop whose condition starts false runs zero times. That is often exactly right: a report of zero days should add nothing.

total += 10 is shorthand for total = total + 10, and -= works the same way. A variable that collects a result across iterations is called an accumulator, and it must be initialized before the loop. If you declare int total = 0; inside the body, a fresh total is created and set to 0 on every iteration, and it disappears at the end of each one.

Accumulator in the wrong place C
#include <stdio.h>

int main(void) {
    for (int day = 0; day < 3; day++) {
        int total = 0;
        total += 20;
        printf("Day %d total: %d\n", day, total);
    }
    return 0;
}
Text
Day 0 total: 20
Day 1 total: 20
Day 2 total: 20

The total never grows. Move the declaration above the for and it prints 20, 40 and 60.

Counting from zero

C programs usually start a counter at 0 and continue while it is less than n. That loop runs exactly n times, with the counter taking the values 0 through n - 1. You will see why on Day 4: array positions start at 0. Both loops below run three times; make the second form your habit.

Two ways to run three times C
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 3; i++) {
        printf("[%d]", i);
    }
    printf("\n");
    for (int i = 0; i < 3; i++) {
        printf("[%d]", i);
    }
    printf("\n");
    return 0;
}
Text
[1][2][3]
[0][1][2]

Each loop printed its pieces on one line, and the printf("\n") after the loop ended it.

while loops and stopping

A while (condition) { body } loop also checks its condition before every repetition, but you initialize before the loop and update inside the body yourself. It fits best when you do not know the number of repetitions in advance.

Every loop needs something in its body that eventually makes the condition false. Forget the update and the condition never changes:

C
int count = 3;
while (count > 0) {
    printf("%d\n", count);
}

This prints 3 forever. In the browser, press Stop to end it. The fix is the missing count--; at the end of the body. When you trace a loop, always ask which statement moves it toward its stopping condition.

A countdown that stops C
#include <stdio.h>

int main(void) {
    int count = 3;
    while (count > 0) {
        printf("%d\n", count);
        count--;
    }
    printf("Go after %d\n", count);
    return 0;
}
Text
3
2
1
Go after 0

The loop body never printed 0: when count became 0, the condition was checked, failed, and control moved to the line after the loop. The counter keeps its final value afterward.

Practice

Exercise

Your turn

You plan to study 15 minutes on day 1 and add 5 minutes more each following day. Use a while loop to print each day's plan and the running total, and stop after the first day on which the running total reaches at least 100 minutes. Then print how many days it took.

Text
Day 1: 15 min, total 15
Day 2: 20 min, total 35
Day 3: 25 min, total 60
Day 4: 30 min, total 90
Day 5: 35 min, total 125
Reached 100 in 5 days
Your workspace C
#include <stdio.h>

int main(void) {
    // Write your solution here.
    return 0;
}
Hint 1: the idea

You need three variables that change together: the day number, that day's minutes and the running total. The loop continues while the total is still below 100.

Hint 2: a first step

Get the stopping right before the formatting: print just day and total once per pass. The last line should be day 5 with a total of 125, and the first should say total 15. If day 1 shows a total of 0, or the loop stops a day early or late, look at what changes before the print in each pass.

Show one solution
C
#include <stdio.h>

int main(void) {
    int day = 0;
    int minutes = 10;
    int total = 0;
    while (total < 100) {
        day++;
        minutes += 5;
        total += minutes;
        printf("Day %d: %d min, total %d\n", day, minutes, total);
    }
    printf("Reached 100 in %d days\n", day);
    return 0;
}
Text
Day 1: 15 min, total 15
Day 2: 20 min, total 35
Day 3: 25 min, total 60
Day 4: 30 min, total 90
Day 5: 35 min, total 125
Reached 100 in 5 days

A while loop fits because you do not know the number of days in advance; the total decides. The condition is checked before each day, so after day 5 it sees 125 and stops. Starting minutes at 10 means the first update produces 15, which keeps all the updates together at the top of the body. In the checkpoint you will separate the work done inside a loop from the verdict printed after it.

Was this article helpful?

Your response is saved on this device.