Skip to main content
eLearner.app
Module 2 · Lesson 2 of 35/18 in the course~12 min
Module lessons (2/3)

Loops

Loops allow repeating the execution of a block of code as long as a condition remains true.

In C++, the standard loops are: for, while, and do-while.

The for Loop

The for loop is used when you know the number of iterations in advance:

Code
// Prints numbers from 0 to 4
for (int i = 0; i < 5; ++i) {
    std::cout << i << " ";
}

The structure of the for loop is split into three parts separated by semicolons ;:

  1. Initialization: run only once at the beginning (e.g. int i = 0).
  2. Condition: evaluated before each iteration; if false, the loop ends (e.g. i < 5).
  3. Update: run at the end of each iteration (e.g. ++i).

The while Loop

The while loop repeats the code as long as its condition is true. It is typically used when the number of iterations is not known beforehand:

Code
int energy = 3;
while (energy > 0) {
    std::cout << "Energy: " << energy << std::endl;
    energy--; // Decrement to prevent an infinite loop
}

The do-while Loop

Unlike the while loop, the do-while loop guarantees that the body of the loop is executed at least once, because the condition is evaluated at the end:

Code
int x = 10;
do {
    std::cout << "Executed!" << std::endl;
} while (x < 5); // Condition is false, loop terminates after the first iteration

Try it yourself

Exercise#cpp.m2.l2.e1
Attempts: 0Loading…

Print numbers from 1 to 5 inclusive, one at a time, using a for loop.

Loading editor…
Show hint

Usa la sintassi `for (int i = 1; i <= 5; ++i) { ... }`.

Solution available after 3 attempts

Exercise#cpp.m2.l2.e2
Attempts: 0Loading…

Given count = 5, use a while loop to print count and decrement it as long as it is greater than 0.

Loading editor…
Show hint

Usa `while (count > 0) { ... }`and don't forget to decrement`count--` inside the loop.

Solution available after 3 attempts