Loops
Loops repeat a block of code while a condition holds, letting you process collections of data or repeat an action a set number of times without duplicating code.
for and while Loops
A for loop is ideal when you know how many times you want to repeat something — it bundles initialisation, condition, and increment in one line. A while loop is better when the number of iterations depends on a condition that changes inside the loop body.
for (int i = 1; i <= 5; i++) {
std::cout << "Count: " << i << std::endl;
}
int attempts = 0;
while (attempts < 3) {
std::cout << "Attempt " << attempts + 1 << std::endl;
attempts++;
}
do-while, break, and continue
A do-while loop guarantees the body runs at least once before checking its condition — useful for menus that must display before validating input. break exits a loop immediately, and continue skips to the next iteration.
int num = 0;
do {
std::cout << "Enter a number (0 to stop): ";
std::cin >> num;
if (num < 0) continue; // skip negative numbers
if (num == 0) break; // stop the loop
std::cout << "You entered: " << num << std::endl;
} while (true);
Common Mistakes
- Writing a loop condition that never becomes false, creating an infinite loop.
- Forgetting to update the loop variable inside a
whileloop. - Using
=instead of==or<=instead of<, causing off-by-one errors. - Confusing
break(exits the loop entirely) withcontinue(skips to the next iteration).
Professional Tip
If you are ever unsure whether a loop will terminate, add a temporary print statement inside it showing the loop variable's value on each pass. This makes infinite loops and off-by-one errors immediately visible.
Your Turn
Write a program that uses a for loop to print the multiplication table (1 through 12) for a number entered by the user.
Mini Quiz
Which loop is guaranteed to execute its body at least once?
do-while loop checks its condition after running the body, so the body always executes at least one time even if the condition is false from the start.