Learn/C++/5. Loops
Lesson 5 of 15
Sign in

C++, lesson 5

Loops

A loop runs the same block of code again and again. C++ has four kinds; they overlap a lot, so pick whichever states your intent most clearly.

The counting for loop

The header has three parts: the init runs once (a variable declared there belongs to the loop alone), the condition is checked before each pass, and the step runs after each pass. Changing the step changes the pattern: i -= 2 counts down in twos, i *= 2 doubles.

++lap and lap++ both add one. As a statement on its own they do the same thing; C++ code traditionally writes ++i.

The range-based for loop

To visit every element of a collection, or every character of a string, use the range-based for. There is no index to get wrong:

2 exercises to try what you just read.

Exercise 1

Collatz steps

Press Ctrl Enter or Check to test your code.

Exercise 2

Guessing game

Press Ctrl Enter or Check to test your code.

You'll use this constantly once you meet std::vector in the collections lesson.

while and do-while

while repeats as long as its condition is true, checking before every pass. It suits loops where you don't know the number of passes in advance:

do { ... } while (condition); checks after the body, so the body always runs at least once.

Reading until the input ends

The expression std::cin >> x is itself usable as a condition: it is true when the read succeeded and false at the end of the input (or on input that isn't a number). That gives a clean idiom for "process every value":

break and continue

break leaves the innermost loop at once. continue skips the rest of the current pass and moves on to the next one.

Nested loops

A loop inside a loop runs the inner loop completely for every pass of the outer one. That's how you walk a grid or print a table. break only exits the inner loop.

Make sure every loop can end: a condition that never becomes false is an infinite loop. Here, programs that run too long are stopped and reported as a time-limit error.

Further reading

  • cppreference: for loop
  • cppreference: Range-based for loop
  • cppreference: while loop
  • cppreference: do-while loop
  • cppreference: break and continue

Start from a positive integer n. If it is even, halve it; if it is odd, replace it with 3n + 1. Repeat until you reach 1. Read n, print the whole sequence on one line separated by spaces, then the number of steps taken.

Use long long for the values: they can climb surprisingly high before falling back.

The first number in the input is the secret. Every number after it is a guess. For each guess print Too low, Too high or Correct!. Stop reading as soon as a guess is correct and then print Got it in <n> guesses. If the input ends before anyone guesses correctly, print Gave up after <n> guesses instead.

for (int lap = 1; lap <= 3; ++lap) {
    std::cout << "Lap " << lap << '\n';
}
std::string word{"loop"};
for (char c : word) {
    std::cout << c << '-';      // l-o-o-p-
}
int population{100};
int years{0};
while (population < 1000) {
    population *= 2;
    ++years;
}
std::cout << years << " years\n";   // 4 years
int value{};
int total{};
while (std::cin >> value) {
    total += value;
}
for (int n = 1; n <= 20; ++n) {
    if (n % 2 == 0) {
        continue;        // skip even numbers
    }
    if (n > 9) {
        break;           // stop after 9
    }
    std::cout << n << ' ';   // 1 3 5 7 9
}
for (int row = 1; row <= 3; ++row) {
    for (int col = 1; col <= row; ++col) {
        std::cout << '*';
    }
    std::cout << '\n';
}
Input:
6
Output:
6 3 10 5 16 8 4 2 1
Steps: 8
Input:
42
50 25 42 10
Output:
Too high
Too low
Correct!
Got it in 3 guesses