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.
#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:
- Initialize a counter once.
- Test the condition before each pass.
- 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.
#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.
#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.
#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.
#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.
#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
- Print the even numbers from 2 to 20 with a
forloop. - Use a
whileloop to double a value until it passes 100, then print the value. - Print a multiplication table from 1 to 5 with nested loops.
- Skip a chosen number with
continueand stop at another withbreak.
