Lesson 7 / 25

Loops

Use Loops confidently by explaining its purpose, trying a small program, and checking the result.

The essential idea

Loops is easier when you first name its job: it helps a program store information, make a decision, or perform a repeatable action. Do not rush to syntax. Ask what value changes, who owns it, and what result you expect.

Trace the loop one pass at a time

Read the code from top to bottom, then run it. The output is evidence, not something to guess.

int sum = 0;
for (int n = 1; n <= 3; ++n) {
  sum += n;
}
std::cout << sum << "\n";

Output:

6
  1. Line 1: The accumulator starts at zero before any number is added.
  2. Line 2: The first valid value is 1, so the loop body may run.
  3. Line 3: This is where the running total changes; it is not printed yet.
  4. Line 4: After the final pass, the completed total is printed once.

A common mistake

Students often treat Loops as a rule to memorize. Instead, compile a four-line example, predict its output, and let the compiler correct your mental model. Compiler errors are precise clues, not a verdict on you.

Check your learning habit.

Quick check: Which is the best way to learn Loops?

  • Build and test one small example.
  • Memorize code without running it.
  • Ignore compiler messages.
Answer

Build and test one small example. — A small program makes cause and effect visible; then you can change one thing and observe it.