Chapter 11 of 48

Loops

Suppose you have to print a 7-times table, add up the marks of 60 students, or keep asking for input until the user types -1. You could copy the same line again and again, but that gets silly fast, and it is impossible when you don't know in advance how many repetitions are needed.

A loop solves this. It tells the computer: "keep running this block of code while some condition is true."

A loop is a control statement that executes a block of statements repeatedly, as long as a given condition remains true.

C++ has four kinds of loops:

  • for loop

  • while loop

  • do-while loop

  • range-based for loop (C++11)

The first three are inherited from C. The fourth was added in C++11 and is the one you will use most often with containers like vector later in the course.

Every loop has the same four parts, even if some of them are written in different places:

1. Initialization  →  set up a counter or starting value
2. Condition       →  checked to decide whether to run the body again
3. Body            →  the work done in each repetition (iteration)
4. Update          →  change something so the condition eventually becomes false

If you forget the update, the condition never changes and the loop runs forever. Keep these four parts in mind; most loop bugs come from getting one of them wrong.


The for Loop

The for loop puts initialization, condition and update on one line, so you can see the whole "plan" of the loop at a glance. It is the natural choice when you know how many times the loop should run.

for (initialization; condition; update) {
    // body
}

Here is a simple example:

#include <iostream>

int main() {
    for (int i = 1; i <= 5; ++i) {
        std::cout << "Iteration " << i << '\n';
    }
    std::cout << "Loop finished\n";
}

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Loop finished

How the for Loop Executes

The order of execution is very important (and a favourite exam question):

        ┌──────────────────┐
        │ int i = 1        │   ← runs ONCE
        └────────┬─────────┘
                 ↓
        ┌──────────────────┐   false
  ┌───→ │  i <= 5 ?        │ ──────────→ exit the loop
  │     └────────┬─────────┘
  │              ↓ true
  │     ┌──────────────────┐
  │     │  body            │
  │     └────────┬─────────┘
  │              ↓
  │     ┌──────────────────┐
  └──── │  ++i             │
        └──────────────────┘
  1. Initialization runs exactly once.

  2. The condition is checked. If it is false, the loop ends immediately (the body may run zero times).

  3. The body runs.

  4. The update runs, and control goes back to step 2.

Let us trace it for the program above:

Step

i

i <= 5

Action

1

1

true

print "Iteration 1", then i becomes 2

2

2

true

print "Iteration 2", then i becomes 3

…

…

…

…

5

5

true

print "Iteration 5", then i becomes 6

6

6

false

loop ends

Notice that the condition is checked 6 times for 5 iterations. A loop that runs n times checks its condition n + 1 times.

Example: Multiplication Table

#include <iostream>

int main() {
    int n = 7;
    for (int i = 1; i <= 10; ++i) {
        std::cout << n << " x " << i << " = " << n * i << '\n';
    }
}

Output:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Flexible Parts of a for Loop

All three parts in the header are optional. These are all valid:

for (int i = 10; i > 0; i -= 2)  { }   // count down in steps of 2
for (int i = 1; i < 1000; i *= 2) { }  // 1, 2, 4, 8, ... (doubling)
for (; x < 100; )                 { }  // same as while (x < 100)
for (;;)                          { }  // no condition = always true (infinite loop)

You can also declare two variables and update both, using a comma:

#include <iostream>

int main() {
    // Two variables in one for loop: i moves right, j moves left
    for (int i = 0, j = 6; i < j; ++i, --j) {
        std::cout << "i = " << i << ", j = " << j << '\n';
    }
}

Output:

i = 0, j = 6
i = 1, j = 5
i = 2, j = 4

This "two pointers moving towards each other" pattern appears a lot in placement coding problems (reversing, palindrome checks, pair sums).

Scope of the Loop Variable

A variable declared in the for header exists only inside the loop. This is a C++ (and C99) rule that keeps the counter from leaking into the rest of the function.

#include <iostream>

int main() {
    for (int i = 0; i < 3; ++i) {
        // i exists only inside this loop
    }
    // std::cout << i;   // error: 'i' was not declared in this scope

    int j = 0;
    for (; j < 3; ++j) { }
    std::cout << "j after the loop = " << j << '\n';
}

Output:

j after the loop = 3

If you need the final value of the counter after the loop, declare it before the loop, as with j.

Tip: Prefer ++i over i++ in the update. For an int they compile to the same code, but for iterators and other class types (later chapters) the prefix form avoids making a needless copy. It is a good habit.


The while Loop

The while loop has only a condition in its header. Use it when you don't know in advance how many iterations are needed and the loop should simply continue "while something is true".

while (condition) {
    // body (must eventually make the condition false)
}

Classic example: work with the digits of a number. We don't know how many digits it has, so a while loop is the natural fit.

#include <iostream>

int main() {
    int n = 4729;
    int sum = 0;
    int reversed = 0;

    while (n > 0) {
        int digit = n % 10;          // last digit
        sum += digit;
        reversed = reversed * 10 + digit;
        n /= 10;                     // drop the last digit
    }

    std::cout << "Sum of digits: " << sum << '\n';
    std::cout << "Reversed: " << reversed << '\n';
}

Output:

Sum of digits: 22
Reversed: 9274

Trace of the loop:

n (start)

digit

sum

reversed

n (end)

4729

9

9

9

472

472

2

11

92

47

47

7

18

927

4

4

4

22

9274

0 → loop ends

Example: GCD with Euclid's Algorithm

Euclid's algorithm repeatedly replaces (a, b) with (b, a % b) until b becomes 0. The number of steps is not obvious beforehand, so again while fits.

#include <iostream>

int main() {
    int a = 252, b = 105;
    std::cout << "gcd(" << a << ", " << b << ") = ";
    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    std::cout << a << '\n';
}

Output:

gcd(252, 105) = 21

(252, 105) → (105, 42) → (42, 21) → (21, 0). It takes only O(log(min(a, b))) steps, which is why this algorithm is so popular.

Example: Reading Until a Sentinel Value

A sentinel is a special value that means "stop". The loop condition below reads a number and checks it in one go. If reading fails (for example, the input ends) std::cin >> value becomes false, so the loop also stops safely.

#include <iostream>

int main() {
    int value;
    int sum = 0, count = 0;
    std::cout << "Enter marks (-1 to stop): ";
    while (std::cin >> value && value != -1) {
        sum += value;
        ++count;
    }
    std::cout << "Count = " << count << ", Sum = " << sum << '\n';
}

Input: 78 92 65 -1

Output:

Enter marks (-1 to stop): Count = 3, Sum = 235

Because && short-circuits (see Operators), value != -1 is checked only after a successful read.


The do-while Loop

In for and while, the condition is checked before the body. In do-while, it is checked after the body. So the body always runs at least once.

do {
    // body
} while (condition);     ← note the semicolon
#include <iostream>

int main() {
    int x = 10;

    while (x < 5) {
        std::cout << "while body\n";      // never runs
    }

    do {
        std::cout << "do-while body, x = " << x << '\n';   // runs once
    } while (x < 5);
}

Output:

do-while body, x = 10

The condition x < 5 is false from the start. The while loop never enters its body; the do-while loop runs it once and only then discovers the condition is false.

When Does "At Least Once" Matter?

Count the digits of a number. The number 0 has one digit, but a while (n != 0) loop would never run for it.

#include <iostream>

int main() {
    int n = 0;

    // Version 1: while
    int temp = n, count1 = 0;
    while (temp != 0) {
        ++count1;
        temp /= 10;
    }

    // Version 2: do-while
    temp = n;
    int count2 = 0;
    do {
        ++count2;
        temp /= 10;
    } while (temp != 0);

    std::cout << "Digits in " << n << " (while)    : " << count1 << '\n';
    std::cout << "Digits in " << n << " (do-while) : " << count2 << '\n';
}

Output:

Digits in 0 (while)    : 0
Digits in 0 (do-while) : 1

For every other non-negative number both versions agree; only the edge case differs. Typical real uses of do-while are menus ("show the menu, then ask whether to repeat") and input validation ("ask, then repeat if the answer was invalid").


Range-Based for Loop (C++11)

Very often we want to visit every element of a collection, and the counter is just a tool to get there. C++11 added a shorter form that removes the counter entirely:

for (declaration : range) {
    // body uses the declared variable
}

Read it as: "for each element in range". It works with arrays, std::string, std::vector and every other STL container (you will see all of these in later chapters), and also with a braced list of values:

#include <iostream>

int main() {
    // C++11: range-based for over a braced list
    int total = 0;
    for (int mark : {78, 92, 65, 88}) {
        total += mark;
    }
    std::cout << "Total marks: " << total << '\n';

    // C++20: range-based for with an init-statement
    for (int i = 1; char c : {'C', '+', '+'}) {
        std::cout << i++ << ':' << c << ' ';
    }
    std::cout << '\n';
}

Output:

Total marks: 323
1:C 2:+ 3:+

The second loop uses a C++20 feature: an init-statement (int i = 1;) before the range, handy when you also want a position number. It is not standard C++ before C++20: with -std=c++17, g++ only warns ("range-based 'for' loops with initializer only available with '-std=c++20'"), and with -pedantic-errors it refuses to compile.

In for (int mark : ...), mark is a copy of each element. To modify elements in place or to avoid copying large objects you write auto& or const auto&; we will use those forms once we reach References and vector.


Nested Loops

A loop inside another loop is a nested loop. For each single iteration of the outer loop, the inner loop runs completely. Think of a clock: the minute hand (inner loop) goes all the way round for every single step of the hour hand (outer loop).

#include <iostream>

int main() {
    int rows = 4;
    for (int i = 1; i <= rows; ++i) {        // outer loop: one row
        for (int j = 1; j <= i; ++j) {       // inner loop: stars in that row
            std::cout << "* ";
        }
        std::cout << '\n';
    }

    std::cout << '\n';
    for (int i = 1; i <= rows; ++i) {
        for (int j = 1; j <= i; ++j) {
            std::cout << j << ' ';
        }
        std::cout << '\n';
    }
}

Output:

*
* *
* * *
* * * *

1
1 2
1 2 3
1 2 3 4

The rule for pattern problems: outer loop = rows, inner loop = what goes in one row. Write down how many items row i has (here, i), and that becomes the inner loop's limit.


Counting Iterations (GATE and Interview Favourite)

Many GATE questions ask "how many times does this statement execute?" or "what is the time complexity?". Let us count three common shapes for n = 100:

#include <iostream>

int main() {
    int n = 100;

    int a = 0;
    for (int i = 1; i < n; i *= 2) ++a;          // doubling

    int b = 0;
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < i; ++j) ++b;         // triangle

    int c = 0;
    for (int i = 0; i < n; ++i)
        for (int j = 1; j < n; j *= 2) ++c;      // n times log n

    std::cout << "doubling: " << a << '\n';
    std::cout << "triangle: " << b << '\n';
    std::cout << "n log n : " << c << '\n';
}

Output:

doubling: 7
triangle: 4950
n log n : 700

Loop shape

Exact count

Complexity

for (i = 0; i < n; ++i)

n

O(n)

for (i = 1; i < n; i *= 2)

⌈log₂ n⌉ (i = 1, 2, 4, …, 64 → 7 for n = 100)

O(log n)

inner j < i inside outer i < n

0 + 1 + … + (n − 1) = n(n − 1)/2 = 4950

O(n²)

independent doubling loop inside i < n

n × ⌈log₂ n⌉ = 100 × 7

O(n log n)

The trick: when loops are nested, multiply if the inner loop does not depend on the outer variable; sum (∑) over the outer variable when it does.


Infinite Loops

A loop whose condition never becomes false is an infinite loop. Sometimes this is intended, for example a server or game loop that runs until the program is closed, and you leave it with break or return (next chapter: Break & Continue):

while (true) {
    // read a command
    // if it is "quit", leave the loop with break
}

for (;;) {
    // same thing, older style
}

Most of the time, though, an infinite loop is a bug: a missing update, an update in the wrong direction, or a condition that can never be false.

A subtle rule: the C++ standard lets the compiler assume that a loop which does no I/O, touches no volatile or atomic variables and performs no synchronization will eventually end. If such a loop actually runs forever, the behaviour is undefined, and an optimizing compiler may even delete the loop. C++26 makes an exception for "trivial" infinite loops such as while (true);. In practice: real infinite loops should do something visible (read input, print, wait), which keeps them well defined.


Choosing the Right Loop

Loop

Condition checked

Minimum runs

Best for

for

before the body

0

a known number of iterations, counting

while

before the body

0

repeat until some event (digits, input, convergence)

do-while

after the body

1

menus, input validation, "do once then maybe repeat"

range-based for (C++11)

automatically, until the end of the range

0

visiting every element of a collection

Any loop can be rewritten as any other, so this is about readability: pick the one that says what you mean.


Common Mistakes

1. A Stray Semicolon After the Header

#include <iostream>

int main() {
    int i;
    for (i = 0; i < 3; ++i);     // stray semicolon: empty loop body
    {
        std::cout << "i = " << i << '\n';
    }
}

Output:

i = 3

The ; is an empty statement, so it becomes the whole loop body. The block below runs only once, after the loop. g++ with -Wall warns about this ("this 'for' clause does not guard..."). Always compile with warnings on.

2. Off-by-One Errors

for (int i = 1; i < 10; ++i) runs 9 times, not 10. When a loop runs from a to b inclusive, it runs b − a + 1 times. Before writing the condition, ask: "should the last value be included?"

3. Counting Down with an unsigned Counter

for (unsigned int i = 3; i >= 0; --i) {   // never ends!
}

An unsigned value is never negative, so i >= 0 is always true. When i is 0, --i wraps around to the largest unsigned value (this wrap-around is well defined for unsigned types). g++ with -Wextra says:

warning: comparison of unsigned expression in '>= 0' is always true [-Wtype-limits]

A correct pattern uses the test-then-decrement trick:

#include <iostream>

int main() {
    unsigned int i = 0;
    --i;                       // unsigned arithmetic wraps around (well defined)
    std::cout << i << '\n';

    // Correct way to count down to 0 with an unsigned counter
    for (unsigned int k = 3; k-- > 0; ) {
        std::cout << k << ' ';
    }
    std::cout << '\n';
}

Output:

4294967295
2 1 0

(4294967295 is 2³² − 1, the largest 32-bit unsigned value.) Or simply use a signed int counter when counting down.

4. Using a Floating-Point Counter

A loop such as for (double x = 0.0; x != 1.0; x += 0.1) may never stop, because 0.1 cannot be stored exactly in binary:

#include <iostream>
#include <iomanip>

int main() {
    double x = 0.0;
    for (int k = 0; k < 10; ++k) {
        x += 0.1;
    }
    std::cout << std::setprecision(17) << x << '\n';
    std::cout << std::boolalpha << (x == 1.0) << '\n';
}

Output:

0.99999999999999989
false

After ten additions, x is not exactly 1.0, so x != 1.0 stays true and the loop would run past 1.0 forever. Use an integer counter and compute the double from it (x = k * 0.1), or compare with < instead of !=.

5. Signed Overflow in the Counter

If a signed int counter goes past INT_MAX (for example for (int i = 1; i > 0; i *= 2)), the behaviour is undefined, not "it becomes negative". The compiler may assume it never happens and produce a loop that never ends. Choose a type large enough for your range (long long) or rewrite the condition.

6. Modifying the Counter Inside the Body

Changing i inside a for body as well as in the update makes the loop very hard to reason about. If you need irregular steps, a while loop states that more honestly.


Interview and GATE Questions

Q1. How many times is the condition checked in for (int i = 0; i < 5; ++i)? How many times does the update run?

The condition is checked 6 times (5 true, 1 false). The update runs 5 times, once after each execution of the body. The initialization runs once.

Q2. What is the output?

int i = 5;
do {
    std::cout << i << ' ';
    i -= 2;
} while (i > 5);

It prints 5 . The body runs once before the condition is tested; then i is 3, 3 > 5 is false, and the loop ends.

Q3. What is the time complexity of this code?

for (int i = n; i > 0; i /= 2)
    for (int j = 0; j < i; ++j)
        ++count;

The inner loop depends on i, so we sum: n + n/2 + n/4 + … ≤ 2n. The answer is O(n), not O(n log n). Multiplying "outer runs log n times" by "inner runs up to n times" gives only an upper bound that is too loose.

Q4. Is for (;;) {} valid C++? What does it do?

Yes. A missing condition is treated as true, so it is an infinite loop. An empty one like this has no observable behaviour, so before C++26 it is technically undefined behaviour under the forward-progress rule; C++26 explicitly allows such trivial infinite loops. Real code puts work and a break or return inside.

Q5. Which loop would you use to show a menu and keep showing it until the user chooses "Exit", and why?

do-while, because the menu has to be shown at least once before we know the user's choice. The condition (choice is not Exit) is naturally checked after the body.

Q6. What does for (int x : {3, 1, 2}) std::cout << x; print, and which standard does it need?

It prints 312: elements are visited in the order written. Range-based for needs C++11 or later.


Summary

  • A loop repeats a block while a condition is true. Every loop has initialization, condition, body and update.

  • for: everything in one header; best when the number of iterations is known. Init runs once; condition is checked before each iteration.

  • while: condition only; best when you loop until some event. May run zero times.

  • do-while: condition checked after the body; always runs at least once. Don't forget the final semicolon.

  • Range-based for (C++11) visits every element of a range; C++20 lets you add an init-statement.

  • Nested loops: the inner loop completes fully for each outer iteration. Multiply counts for independent loops; sum them when the inner depends on the outer.

  • Watch out for stray semicolons, off-by-one limits, unsigned count-downs, floating-point counters and signed overflow.

Know your count, pick the loop that states your intent, and make sure something in the body moves you towards the exit.