Register

C++ for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Loops and repetition

Starting out11 min readLesson 5 of 6

5.1 Repeating a block

A loop repeats statements while a condition holds. Every loop needs a way to stop: a counter that changes, a value that reaches a target, or a condition that becomes false. A loop that never changes its condition keeps running until you stop the program.

The three loop forms in beginner C++ are for, while, and do while. They can all express the same repetition. Choose the form that makes the stopping rule easiest to see.

cpp
#include <iostream>

int main() {
    int total = 0;
    for (int i = 1; i <= 5; ++i) {
        total += i;
        std::cout << "i = " << i << "\n";
    }
    std::cout << "Total: " << total << "\n";
    return 0;
}

Output

i = 1
i = 2
i = 3
i = 4
i = 5
Total: 15

5.1.1 The for loop

A for loop places three pieces on one line:

  1. Initialize a counter once.
  2. Test the condition before each pass.
  3. Update the counter after each pass.

for (int i = 1; i <= 5; ++i) runs five times. The variable i exists only inside the loop. If you need its final value after the loop, declare the variable before the loop.

The off-by-one mistake is common. i < 5 and i <= 5 differ by one pass. Decide whether you want an inclusive upper bound and test the first and last values.

cpp
#include <iostream>

int main() {
    for (int second = 5; second >= 1; --second) {
        std::cout << second << " ";
    }
    std::cout << "Go!\n";
    return 0;
}

Output

5 4 3 2 1 Go!

5.1.2 The while loop

A while loop tests its condition before each pass. Use it when the number of passes depends on changing data. Update the tested value inside the body, or the condition never changes.

A loop such as while (savings < target) is easy to read because the stopping rule sits at the top. Print the changing variable inside the loop while testing so you can see it move toward the target.

cpp
#include <iostream>

int main() {
    int savings = 10;
    const int target = 50;
    int weeks = 0;
    while (savings < target) {
        savings += 10;
        ++weeks;
    }
    std::cout << "Weeks: " << weeks << "\n";
    std::cout << "Total: " << savings << "\n";
    return 0;
}

Output

Weeks: 4
Total: 50

5.1.3 The do while loop

A do while loop runs its body once, then tests the condition. The test sits at the bottom and needs a semicolon after the closing parenthesis. It fits a menu or a retry step that must happen at least once.

Most beginner loops can use for or while. Reach for do while when the first pass is guaranteed and the check belongs after the work.

cpp
#include <iostream>

int main() {
    int step = 1;
    do {
        std::cout << "Step " << step << "\n";
        ++step;
    } while (step <= 3);
    return 0;
}

Output

Step 1
Step 2
Step 3

5.1.4 Leaving early and skipping work

break exits the nearest loop immediately. continue skips the rest of the current pass and starts the next test. Both make a loop easier to read when they handle a clear special case, and harder when scattered through nested blocks.

Prefer a condition that says what should happen. A loop whose only exit sits inside a deep if takes more effort to trace than one with a clear top condition.

cpp
#include <iostream>

int main() {
    for (int i = 1; i <= 6; ++i) {
        if (i == 2) {
            continue;
        }
        if (i == 5) {
            break;
        }
        std::cout << "Number " << i << "\n";
    }
    return 0;
}

Output

Number 1
Number 3
Number 4

5.1.5 Nested loops

A loop inside another loop runs completely for each pass of the outer loop. A table with rows and columns is a natural fit. The total number of passes is the product of the two counts, so nested loops grow quickly.

Name counters by role, as in row and col, and keep the inner work short. If a nested loop needs several conditions, consider moving the work into a function once functions are covered.

cpp
#include <iostream>

int main() {
    for (int row = 1; row <= 3; ++row) {
        for (int col = 1; col <= row; ++col) {
            std::cout << "*";
        }
        std::cout << "\n";
    }
    return 0;
}

Output

*
**
***

5.1.6 Choosing and testing

  • Known number of passes: start with for.
  • Unknown number of passes: start with while.
  • Body must run once before a check: do while.
  • Early exit for one special value: break.

Test a loop with a small number of passes, then check the first value, last value, and the case where the loop should run zero times. Add a temporary print inside the body when the count is wrong.

5.1.7 Practice

  1. Print the even numbers from 2 to 20 with a for loop.
  2. Use a while loop to double a value until it passes 100, then print the value.
  3. Print a multiplication table from 1 to 5 with nested loops.
  4. Skip a chosen number with continue and stop at another with break.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01When should you use a for loop instead of a while loop?

    Use for when the initialization, test, and update of a counter belong together. Use while when the loop depends on a value that changes in less predictable steps.

  • 02What is an off-by-one error?

    It is a loop boundary mistake. The condition runs one pass too many or too few, often because < was used where <= was intended or the starting value was wrong.

  • 03What does break do inside nested loops?

    It leaves only the nearest enclosing loop. The outer loop continues with its next pass unless another break or condition stops it.