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:
// 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 ;:
- Initialization: run only once at the beginning (e.g.
int i = 0). - Condition: evaluated before each iteration; if false, the loop ends (e.g.
i < 5). - 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:
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:
int x = 10;
do {
std::cout << "Executed!" << std::endl;
} while (x < 5); // Condition is false, loop terminates after the first iteration
Try it yourself
Print numbers from 1 to 5 inclusive, one at a time, using a for loop.
Show hint
Usa la sintassi `for (int i = 1; i <= 5; ++i) { ... }`.
Solution available after 3 attempts
Given count = 5, use a while loop to print count and decrement it as long as it is greater than 0.
Show hint
Usa `while (count > 0) { ... }`and don't forget to decrement`count--` inside the loop.
Solution available after 3 attempts