Skip to content

Beginner · Decisions, loops and functions · topic 6 of 42 · 25 min

Loops: for, while, do-while and range-for

Explanation

Loops repeat code. for is best when you know how many times; while repeats while a condition is true; do-while runs at least once. The range-based for loop walks over every item of a container. break leaves a loop and continue skips to the next round.

Why loops?

Printing a multiplication table, adding the marks of 60 students or retrying a password are all "do this again and again" jobs. A loop repeats a block of code. Each repetition is called an iteration.

The for loop

cpp
for (int i = 1; i <= 5; ++i) {
    std::cout << "7 x " << i << " = " << 7 * i << '\n';
}
Three parts: start (int i = 1), condition checked before each round (i <= 5), and update after each round (++i). Prints the 7 table from 1 to 5.

++i adds 1 to i. In a for loop's update part, ++i and i++ do the same thing; many C++ programmers prefer ++i as a habit because for some types (iterators) it avoids a copy.

while and do-while

cpp
int balance = 1000;
int months = 0;
while (balance < 2000) {          // checked BEFORE each round
    balance = balance * 110 / 100;
    ++months;
}
std::cout << months << " months\n";    // 8

int pin;
do {
    std::cout << "Enter PIN: ";
    std::cin >> pin;
} while (pin != 1234);            // checked AFTER each round, so it runs at least once
Use while when you do not know the number of rounds; do-while when the body must run at least once (like asking for input).

Range-based for

cpp
#include <vector>
std::vector<int> marks = {78, 91, 64, 85};
int total = 0;
for (int m : marks) {
    total += m;
}
std::cout << "Total: " << total << '\n';   // 318
for (type name : container) visits every item. It cannot go out of range, so prefer it when you need each item.

Here std::vector is a list that can grow; you will study it fully in the STL module. For now, think of it as a row of boxes.

break and continue

cpp
for (int n = 1; n <= 10; ++n) {
    if (n % 2 == 0) continue;   // skip even numbers
    if (n > 7) break;           // stop the whole loop
    std::cout << n << ' ';
}
// prints: 1 3 5 7
continue jumps to the next iteration; break exits the loop at once.

Nested loops

cpp
for (int row = 1; row <= 3; ++row) {
    for (int col = 1; col <= row; ++col) {
        std::cout << '*';
    }
    std::cout << '\n';
}
The inner loop runs fully for each round of the outer loop. Prints a small triangle of stars: *, **, ***.
Think of it like this: A nested loop is like a clock. The minute hand (inner loop) goes all the way round 60 times for each single step of the hour hand (outer loop).

Common mistakes

  • Off-by-one: for (int i = 0; i <= n; ++i) runs n + 1 times. To visit n items indexed 0..n-1, use i < n.
  • Infinite loop: forgetting to change the variable in a while loop, so the condition stays true forever. Press Ctrl+C to stop the program.
  • Comparing a signed int with v.size() (which is unsigned) gives a warning. Use for (std::size_t i = 0; i < v.size(); ++i) or a range-for.
  • A semicolon after the loop header: for (...); { } runs an empty body many times and the block once.
Tip: Nested loops multiply work: two loops of 1,000 rounds each make 1,000,000 steps. Keep this in mind for big inputs; you will measure it properly with Big-O in the DSA module.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Loops: for, while, do-while and range-for · 1/6

Loops

Loops let a program repeat work without copying code. Let us meet the four kinds of loop in C++.

Prefer a video by a teacher? Find free videos on “c++ for while do while range based for loop tutorial” on YouTube ↗

In real life: EMI schedule for a phone

When you buy a phone on EMI, the shop prints a schedule: month 1, month 2 and so on, with the amount left after each payment. A for loop over the months, with a running balance, produces exactly that table.

cpp
#include <iostream>

int main() {
    int price = 24000, months = 6;
    int emi = price / months;
    int left = price;
    for (int m = 1; m <= months; ++m) {
        left -= emi;
        std::cout << "Month " << m << ": paid " << emi << ", left " << left << '\n';
    }
}
Prints six lines, ending with Month 6: paid 4000, left 0.

Practice (0/4 done)

Task 1 · Question

How many times does this print "Hi"? for (int i = 0; i < 4; ++i) std::cout << "Hi";

Task 2 · Question

What does this print? int s = 0; for (int i = 1; i <= 5; ++i) { if (i == 3) continue; s += i; } std::cout << s;

Task 3 · Question

Which loop is the best choice to keep asking for a PIN until it is right?

Task 4 · Practice

Write a program that reads a number n and prints the sum of its digits (for 4521 the answer is 12). Then extend it to print whether n is a palindrome (reads the same backwards, like 1221).

Quick quiz

Question 1

1.Which loop always runs its body at least once?

Question 2

2.What does break do inside a loop?

Question 3

3.for (int i = 0; i <= 10; i += 2) runs how many times?

Question 4

4.Two nested loops each run 1,000 times. How many times does the inner body run?

Question 5

5.Why does for (int x : v) avoid out-of-range bugs?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which loop always runs its body at least once?

Answer: do-while

do-while checks its condition after the body.

What does break do inside a loop?

Answer: Exits the loop immediately

break leaves the innermost loop (or switch) at once.

for (int i = 0; i <= 10; i += 2) runs how many times?

Answer: 6

i = 0, 2, 4, 6, 8, 10: six rounds.

Two nested loops each run 1,000 times. How many times does the inner body run?

Answer: 1,000,000

The inner loop runs fully for every outer round: 1,000 × 1,000.

Why does for (int x : v) avoid out-of-range bugs?

Answer: It has no index; it visits exactly the items in the container

A range-for walks from the first to the last element, so there is no index to get wrong.

Which loop always runs its body at least once?Related

Answer: do-while

do-while checks the condition after the body.

From Loops and ranges

Which loop is best to visit every item of an array?Related

Answer: for...of

for...of gives you each item in turn, with no index to manage.

From Loops: repeating work

Which loop always runs its body at least once?Related

Answer: do…while

do…while checks the condition after the first run.

From Loops: for, while, do…while, for…of and for…in

Which loop always runs its body at least once?Related

Answer: do-while

do-while checks the condition after the body.

From Loops: for, while, do-while and foreach

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Decisions, loops and functions” before its exam: Functions: declare, define, call and return, Overloading, default arguments and recursion.
  2. Module 2 exam: Decisions, loops and functions · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, References, pointers, arrays and strings. 42 topics left in the course before the final exam.

← Previous: Operators and decisions: if, else and switch