Loops: while, do-while & for
while — repeat while a condition is true
while (condition) { ... }
The condition is checked before each iteration (may run zero times).
do-while — runs at least once
do { ... } while (condition); // note the semicolon
Perfect for menus and "ask until valid" input.
for — counting loops
for (init; condition; update) { ... }
for (int i = 0; i < 10; ++i) { ... }
initruns once; the variable is local to the loopconditionchecked before each iterationupdateruns after each iteration- Any part may be empty:
for (;;)is an infinite loop
Which loop?
| Situation | Loop |
|---|---|
| Known number of repetitions | for |
| Repeat until something happens | while |
| Must run at least once | do-while |
| Every element of a container | range-based for (next lesson) |
Infinite loops
while (true) { ... if (done) break; } — fine when there's a clear exit.
Accidental infinite loops: forgetting to update the variable, or the wrong comparison.
Off-by-one errors ⚠️
i <= nvsi < n— for an array of size n, valid indexes are 0 … n−1- Count iterations in your head for a small case (n = 3)
Loop with unsigned counters
for (std::size_t i = v.size() - 1; i >= 0; --i) // ❌ infinite: unsigned is always >= 0
Count down with a signed type, or use for (std::size_t i = v.size(); i-- > 0; ).
Accumulator patterns
- Sum:
total += x; - Count:
if (cond) ++count; - Max/min:
if (x > best) best = x; - Product, average, running balance
Example
#include <iostream>
int main() {
// for: a monthly savings plan
double saved = 0;
for (int month = 1; month <= 6; ++month) {
saved += 2500;
std::cout << "Month " << month << ": Rs. " << saved << '\n';
}
// while: how many months until a goal with 1% monthly interest?
double balance = 10000, goal = 11000;
int months = 0;
while (balance < goal) {
balance *= 1.01;
++months;
}
std::cout << "Goal reached after " << months << " months\n";
// do-while: runs at least once
int attempts = 0;
int pin_guesses[] = { 1111, 2580, 1234 };
int guess;
do {
guess = pin_guesses[attempts++];
std::cout << "Trying PIN " << guess << '\n';
} while (guess != 1234 && attempts < 3);
std::cout << (guess == 1234 ? "Unlocked" : "Locked out") << " after " << attempts << " attempts\n";
// counting down with a signed counter
for (int i = 3; i >= 1; --i) std::cout << i << "... ";
std::cout << "Go!\n";
// sum of digits
int n = 2026, digit_sum = 0;
while (n > 0) { digit_sum += n % 10; n /= 10; }
std::cout << "Digit sum of 2026 = " << digit_sum << '\n';
return 0;
}
/* Output:
Month 1: Rs. 2500
Month 2: Rs. 5000
Month 3: Rs. 7500
Month 4: Rs. 10000
Month 5: Rs. 12500
Month 6: Rs. 15000
Goal reached after 10 months
Trying PIN 1111
Trying PIN 2580
Trying PIN 1234
Unlocked after 3 attempts
3... 2... 1... Go!
Digit sum of 2026 = 10
*/