Skip to content

Repeat with a Loop

The Course
•
35 min study

A week of study is seven days of the same kind of work. Writing seven nearly identical lines works once, but it is slow to change and easy to get wrong: miss one line and the total is off. A loop states the repeated work once and lets the program run it as many times as needed. Change the count from 7 to 30 and nothing else has to change.

A for loop has three parts in its parentheses. The initialization runs once, before anything else. The condition is checked before each iteration; when it is false, the loop ends. The update runs after each iteration's body. ++day adds one to day, and total += 15 adds 15 to the existing total.

Predict and run

Trace day and total on paper, one row per iteration, before you run.

Predict before running C++
#include <iostream>

int main() {
    int total = 0;
    for (int day = 1; day <= 3; ++day) {
        total += 15;
        std::cout << day << ": " << total << "\n";
    }
    return 0;
}
Check your prediction
Text
1: 15
2: 30
3: 45

After the third iteration, the update makes day equal to 4, the condition 4 <= 3 is false, and the loop ends. The body ran three times, not four. Change <= to < and predict how many lines remain before you run.

Where the accumulator lives

An accumulator is a variable that collects a result across iterations, like total. It must be declared and initialized before the loop. If you declare it inside the body, a fresh variable is created and set to zero on every iteration, so it can never accumulate anything.

Accumulator inside versus outside C++
#include <iostream>

int main() {
    for (int day = 1; day <= 3; ++day) {
        int total = 0;          // wrong: reset each time
        total += 15;
        std::cout << "inside: " << total << "\n";
    }

    int total = 0;              // right: survives every iteration
    for (int day = 1; day <= 3; ++day) {
        total += 15;
    }
    std::cout << "outside: " << total << "\n";
    return 0;
}
Text
inside: 15
inside: 15
inside: 15
outside: 45

Scope explains it. A variable declared between a pair of braces lives only until the closing brace. The body's braces close at the end of every iteration, so the inner total is destroyed and recreated three times. The same rule applies to the loop counter: day exists only inside the for statement, so you cannot print it after the loop ends.

while loops

A while loop checks a condition before each iteration, like for, but has no built-in initialization or update. You write those yourself: declare the counter before the loop and change it inside the body. Use while when you do not know in advance how many iterations you need, such as "keep adding sessions until the goal is reached."

Repeat until a goal C++
#include <iostream>

int main() {
    const int goal = 60;
    int total = 0;
    int sessions = 0;
    while (total < goal) {
        total += 25;
        ++sessions;
    }
    std::cout << sessions << " sessions, " << total << " minutes\n";
    return 0;
}
Text
3 sessions, 75 minutes

After two sessions the total is 50, still below 60, so a third session runs. The loop stops only when the condition is checked and found false, which is why the total can overshoot the goal.

Every loop must be able to stop

If nothing in the body moves the condition toward false, the loop runs forever. Forgetting ++sessions is harmless above, but forgetting total += 25 would make total < goal true forever. In this browser, Stop ends such a run. Before you run a new loop, ask two questions: what makes the condition false, and does every iteration move toward that?

Off-by-one mistakes are the other common loop bug. day <= 3 starting at 1 runs three times; day < 3 starting at 1 runs twice; day <= 3 starting at 0 runs four times. When the count matters, trace the first and last iteration explicitly.

Practice

Exercise

Your turn

Plan five days of practice. Day 1 is 10 minutes, and each later day is 5 minutes longer than the day before. Print one line per day and a total:

  • Day 1: 10 min
  • Day 2: 15 min
  • Day 3: 20 min
  • Day 4: 25 min
  • Day 5: 30 min
  • Total: 100 min

Use one loop and calculate the minutes; do not type the five values.

Your workspace C++
#include <iostream>

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

Two values change each iteration: the day's minutes grow by 5, and the total grows by that day's minutes. Both need to be declared before the loop.

Hint 2: a first step

Start with int minutes = 10; and int total = 0;, then write for (int day = 1; day <= 5; ++day) and print the line before updating minutes.

Show one solution
Run the solution C++
#include <iostream>

int main() {
    int minutes = 10;
    int total = 0;
    for (int day = 1; day <= 5; ++day) {
        std::cout << "Day " << day << ": " << minutes << " min\n";
        total += minutes;
        minutes += 5;
    }
    std::cout << "Total: " << total << " min\n";
    return 0;
}
Text
Day 1: 10 min
Day 2: 15 min
Day 3: 20 min
Day 4: 25 min
Day 5: 30 min
Total: 100 min

The order inside the body matters: the day is printed and added to the total before minutes grows for the next day. Move minutes += 5; to the top of the body and every line shifts by 5, giving a total of 125. The total line sits after the loop's closing brace, so it prints once. In the checkpoint you will combine a loop like this with a final decision.

Was this article helpful?

Your response is saved on this device.