Loops
Computers are good at doing the same job many times without getting bored: printing every student's result, adding up a month of sales, checking every seat in a train coach. A loop repeats a block of code while a condition stays true. C++ has four loop forms, and each one fits a different kind of problem.
In this lesson you will learn while, do-while, the counting for loop and the modern range-based for, plus break, continue and nested loops.
The while loop
A while loop checks its condition first and repeats the body as long as the condition is true. Use it when you do not know in advance how many repetitions you need.
#include <print>
int main() {
int savings = 0;
int months = 0;
while (savings < 10000) {
savings += 1500; // Rohan saves Rs. 1500 a month
++months;
}
std::println("Goal reached in {} months with Rs. {}", months, savings);
}Goal reached in 7 months with Rs. 10500
After 6 months the savings are 9000, still below 10000, so the loop runs once more. After the seventh month the savings are 10500, the condition becomes false and the loop stops. Something inside the body must eventually make the condition false; otherwise you get an infinite loop and the program never finishes (press Ctrl+C to stop it).
The do-while loop
A do-while loop checks its condition after the body, so the body always runs at least once. That suits tasks like counting the digits of a number, where even 0 has one digit.
#include <print>
int main() {
int number = 2026;
int digits = 0;
do {
++digits;
number /= 10; // drop the last digit
} while (number != 0);
std::println("Digits: {}", digits);
}Digits: 4
The number goes 2026, 202, 20, 2, 0, so the body runs four times. With number = 0, a while loop would never run its body and report 0 digits; the do-while correctly reports 1. Do not forget the semicolon after while (...) in this form.
The for loop
When you know how many times to repeat, the counting for loop keeps everything about the counter in one line: start value, condition and update.
#include <print>
int main() {
for (int i = 1; i <= 5; ++i) {
std::println("7 x {} = {}", i, 7 * i);
}
}7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
The three parts are: int i = 1 runs once at the start; i <= 5 is checked before every repetition; ++i runs after every repetition. The counter i exists only inside the loop.
Range-based for: looping over a collection
Most of the time you loop to visit every item in a collection. The range-based for loop (C++11) does exactly that without any counter. Here the collection is a std::vector, a list of values that you will study in Arrays, std::array & std::vector.
#include <print>
#include <string>
#include <vector>
int main() {
std::vector<std::string> stops = {"Rohtak", "Jind", "Jaipur"};
for (const auto& stop : stops) {
std::println("Train stops at {}", stop);
}
for (int n = 1; const auto& stop : stops) { // C++20: with an initializer
std::println("{}. {}", n, stop);
++n;
}
std::string word = "PUNE";
for (char letter : word) {
std::print("{}-", letter);
}
std::println("");
}Train stops at Rohtak Train stops at Jind Train stops at Jaipur 1. Rohtak 2. Jind 3. Jaipur P-U-N-E-
Read for (const auto& stop : stops) as "for each stop in stops". const auto& means "use each item directly, without copying it, and do not change it". For small types such as char or int, a plain copy (char letter) is fine. If you want to change the items, drop the const: for (auto& price : prices) { price += 10; }. Since C++20 you can add an initializer before the loop variable, which is handy for numbering items.
break and continue
break leaves the loop immediately. continue skips the rest of the current repetition and moves on to the next one.
#include <print>
int main() {
for (int roll = 1; roll <= 10; ++roll) {
if (roll % 3 == 0) {
continue; // skip roll numbers 3, 6 and 9
}
if (roll == 8) {
break; // stop completely at 8
}
std::print("{} ", roll);
}
std::println("");
}1 2 4 5 7
Roll numbers 3 and 6 are skipped by continue. When roll reaches 8, break ends the loop, so 8, 9 and 10 are never printed.
Nested loops
A loop can sit inside another loop. The inner loop runs completely for every single repetition of the outer loop. Pattern questions like this one are popular in Indian school and college exams:
#include <print>
int main() {
for (int row = 1; row <= 4; ++row) {
for (int col = 1; col <= row; ++col) {
std::print("{} ", col);
}
std::println("");
}
}1 1 2 1 2 3 1 2 3 4
On row 1 the inner loop runs once, on row 2 twice, and so on. break inside the inner loop leaves only the inner loop, not the outer one.
Common mistakes
- Off-by-one errors.
for (int i = 0; i <= 5; ++i)runs six times, not five. With indexes from 0, the usual pattern isi < count. - Forgetting to update the counter in a
whileloop. The condition never changes and the loop runs forever. - Counting down with an unsigned type.
for (std::size_t i = n - 1; i >= 0; --i)never ends, because an unsigned value is always>= 0; it wraps round to a huge number instead of going negative. - Changing a vector's size inside a range-based
forover it. Adding or removing items while looping over the same vector can make the loop read freed memory. Collect changes and apply them after the loop.
Key points
whilechecks first and may run zero times;do-whilealways runs at least once.- The counting
forloop keeps start, condition and update in one line. - Range-based
for (const auto& item : items)visits every item without an index; C++20 allows an initializer before the loop variable. breakexits the loop;continuejumps to the next repetition.- In nested loops, the inner loop completes fully for each outer repetition.
Exercise
A shopkeeper in Lucknow records daily sales in std::vector<int> sales = {1200, 0, 3400, 2800, 0, 5100, 4300};. Write a program that uses a range-based for loop to add up the total, skips days with no sales using continue, counts how many days had sales, and prints the total and the average per selling day with two decimal places.
Show solution
#include <print>
#include <vector>
int main() {
std::vector<int> sales = {1200, 0, 3400, 2800, 0, 5100, 4300};
int total = 0;
int selling_days = 0;
for (int amount : sales) {
if (amount == 0) {
continue;
}
total += amount;
++selling_days;
}
std::println("Total: Rs. {}", total);
std::println("Average per selling day: Rs. {:.2f}", static_cast<double>(total) / selling_days);
}Total: Rs. 16800 Average per selling day: Rs. 3360.00
Five days had sales, and 16800 / 5 = 3360. The cast to double keeps the decimals in case the average is not a whole number.
Quick Quiz
1. Which loop always runs its body at least once?
do-while checks its condition after the body, so the body runs before the first check.
2. How many times does for (int i = 0; i < 4; ++i) repeat?
i takes the values 0, 1, 2 and 3; when it becomes 4 the condition is false.
3. What does continue do inside a loop?
continue jumps to the next repetition; break leaves the loop.
4. In for (const auto& city : cities), why use const auto&?
A reference avoids copying each string, and const prevents accidental changes.
Learn C++ with a mentor
Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
