TeachMate
My ProgressJoin Session

Loops

0/11 completed · ~1h 1m

All Topics
C++LearnLoopsSyllabus
1 / 11

Loops

beginner
6 min read

What you'll learn

  • Explain why a loop replaces repeated statements.
  • Write a for, while, or do-while loop that terminates correctly.
  • Trace a loop and predict its output before running it.

Loops repeat a block of code multiple times. They are one of the most fundamental control structures in programming.

Problem

You must print the numbers 1 to 10. Writing them by hand looks like this:

Goal: Print 1 through 10 with a single repeating statement instead of ten separate lines.

cout << 1 << " ";
cout << 2 << " ";
cout << 3 << " ";
// ...seven more lines...
cout << 10 << " ";

Ten near-identical lines is slow and easy to get wrong. Look for the pattern:

Pseudocode
START
  set i = 1
  WHILE i <= 10
    print i
    i = i + 1
END

C++ expresses 'repeat' with a loop:

for (int i = 1; i <= 10; i++) {
    cout << i << " ";
}

Now that the reason is clear, the rest of this note explains the syntax and the three loop types.

Why Loops Matter

  • Avoid repeating the same code for similar tasks
  • Process collections of data (arrays, strings, files)
  • Implement algorithms (searching, sorting, aggregation)
  • Create repetitive behaviors (animations, polling, retries)

Three Types of Loops

  1. for loop: when you know the number of iterations
  2. while loop: when you don't know iterations, check before each
  3. do-while loop: execute at least once, then check

for Loop

for (int i = 0; i < 5; i++) {
    cout << i << " ";
}

while Loop

int i = 0;
while (i < 5) {
    cout << i << " ";
    i++;
}

do-while Loop

int i = 0;
do {
    cout << i << " ";
    i++;
} while (i < 5);

Infinite Loops

while (true) { ... }     // Runs forever (use break to exit)
for (;;) { ... }          // Same as while(true)

Complete Program: Three Ways to Count to 5

#include <iostream>

int main() {
    for (int i = 1; i <= 5; ++i) std::cout << i << ' ';
    std::cout << '\n';

    int j = 1;
    while (j <= 5) { std::cout << j << ' '; ++j; }
    std::cout << '\n';

    int k = 1;
    do { std::cout << k << ' '; ++k; } while (k <= 5);
    std::cout << '\n';

    return 0;
}

Common mistakes: forgetting the update step so a while loop never terminates, an off-by-one bound (i <= n vs i < n) that runs one iteration too many, and dropping the semicolon after do-while(...).

Key takeaway: Choose the right loop type — for when you know the count, while for unknown iterations, and do-while when you need at least one execution.

Try it: Write a program that uses each of the three loop types (for, while, do-while) to print numbers 1 through 5.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects