Loops in C++: for, while and do-while with Step-by-Step Examples

Trace how C++ loops test, execute and update. Compare a zero-iteration case, understand copies and references, and practise predicting outputs without losing track of break or continue.

KnowledgeGate Team

Exam prep & CS education

Updated 20 Nov 20266 min read
Loops in C++: for, while and do-while with Step-by-Step Examples

C++ offers classic for, while, and do-while loops, and each places its condition, body, and update at a different point. The traces below add 1 through 4, compare an initially false condition, and show how continue differs from break. This C++ treatment adds range-based traversal and copies versus references; Loops in C: for, while and do-while with worked examples covers the C syntax counterpart. It is a practical starting point among our Coding & Skills tutorials and courses.

C++ loops: choose by when they check and what repeats

An iteration is one pass through a loop body. With i = 1, the condition i <= 4 decides whether to continue, and ++i advances the counter. An update can also decrement a value or change another part of the state.

Loop

Check or traversal

Minimum body entries

Convenient for

Classic for

Check before body

0

Counters and indices

while

Check before body

0

Condition-driven work

do-while

Check after body

1

Work before checking

Range-based for

Visit each element

0 for an empty range

Whole-range traversal

These are readability choices. A for loop does not require a known iteration count, and a while loop can count precisely.

Trace a for loop: add 1, 2, 3 and 4

This complete program accumulates each counter value in sum:

cpp
#include <iostream>

int main() {
    int sum = 0;
    for (int i = 1; i <= 4; ++i) {
        sum += i;
    }
    std::cout << sum << '\n';
}

The output is 10. Initialisation happens once. After that, the condition, body and update repeat in that order, following the C++ working draft's iteration rules.

i at test

i <= 4

sum before

sum after body

i after update

1

true

0

1

2

2

true

1

3

3

3

true

3

6

4

4

true

6

10

5

5

false

10

not executed

not executed

Read the additions as 0+1=1, 1+2=3, 3+3=6, then 6+4=10. There are four body executions but five condition checks. The last check stops the loop; it adds nothing. The header's i is outside its scope after the loop.

Flowchart showing a C++ for loop adding 1 through 4 and reaching sum 10.

Compare while and do-while using the same values

For each following snippet, use a fresh int main() with #include <iostream> above it.

The while version places initialisation before the loop and the update inside it:

cpp
int sum = 0, i = 1;
while (i <= 4) {
    sum += i;
    ++i;
}
std::cout << sum << ' ' << i << '\n';

It prints 10 5. Now move the check below the body:

cpp
int sum = 0, i = 1;
do {
    sum += i;
    ++i;
} while (i <= 4);
std::cout << sum << ' ' << i << '\n';

This also prints 10 5. Notice the required semicolon after the do-while condition.

For a fresh boundary case, start with int i = 5, visits = 0;. Use condition i <= 4 and body { ++visits; ++i; }. A while finishes with visits=0, i=5; a do-while finishes with visits=1, i=6. Avoid do-while when an initially false condition must prevent all work. Readers comparing shared syntax can also study loops in C.

Panels compare while and do-while when the initial condition is false; do-while runs once.

Use range-based for when you need every array element

Available from C++11, range-based for traverses elements without an explicit index:

cpp
int marks[] = {6, 8, 10};
int total = 0;
for (int mark : marks) {
    total += mark;
}
std::cout << total << '\n';

The total moves 0 -> 6 -> 14 -> 24, so this prints 24.

On a fresh array, compare a copy with a reference:

cpp
int marks[] = {6, 8, 10};
for (int mark : marks) {
    mark += 2;
}
for (int& mark : marks) {
    mark += 2;
}

The first loop leaves {6,8,10} unchanged: mark is a copy. The second changes the array to {8,10,12}: int& names the original element. Use the C++ learning path to place arrays and references in context.

Follow break and continue without losing the update

Predict which values reach the output statement:

cpp
for (int i = 1; i <= 6; ++i) {
    if (i == 3) { continue; }
    if (i == 5) { break; }
    std::cout << i << ' ';
}

The output values are 1 2 4. At 3, continue skips printing but still reaches ++i. At 5, break exits before printing or updating; 6 is never reached.

The working draft's continue statement targets the innermost loop's continuation point: the update in classic for, or the condition in while and do-while. Its break statement exits the nearest enclosing loop or switch, not an entire function or every nested loop.

Here is a safe while adaptation:

cpp
int i = 0;
while (i < 6) {
    ++i;
    if (i == 3) { continue; }
    if (i == 5) { break; }
    std::cout << i << ' ';
}

It also prints 1 2 4. Updating before the possible continue preserves progress here.

Fix boundary, update and empty-body mistakes

Off-by-one access: for int a[] = {6,8,10};, valid indices are 0, 1 and 2. Using i <= 3 while indexing attempts a[3]. That is undefined behaviour, not a guaranteed crash or predictable value. Use i < 3.

Skipped update: examine this faulty loop:

cpp
int i = 1;
while (i <= 3) {
    if (i == 2) { continue; }
    std::cout << i;
    ++i;
}

It sends 1 to the output stream, then stays at i=2: every continue skips ++i. Ensure progress before every such jump, as in the previous section.

Accidental semicolon: this loop has an empty body:

cpp
int i = 0;
for (; i < 3; ++i);
{
    std::cout << i;
}

It prints 3 once because the separate block runs after the loop. Remove the header's trailing semicolon to print 012. The do-while terminator, by contrast, is required.

Practise the output-tracing skills used in assessments

These are original practice tasks. Predict the final values before reading the answers.

cpp
int s = 0;
for (int i = 2; i <= 8; i += 2) {
    s += i;
}

Answer: s=20: 0+2=2, 2+4=6, 6+6=12, 12+8=20.

cpp
int n = 0;
do {
    ++n;
} while (n < 0);

Answer: n=1. The body runs before the false test 1 < 0.

cpp
int count = 0;
for (int r = 1; r <= 2; ++r) {
    for (int c = 1; c <= 3; ++c) {
        if (c == 2) { break; }
        ++count;
    }
}

Answer: count=2. The visited pairs are (1,1), (1,2), (2,1), (2,2). Each c=1 adds one; each c=2 breaks only the inner loop, following the working-draft rule above.

Record initial state, condition, executed statements and next state. This makes your reasoning checkable.

Short version and your next practice step

Use classic for for an explicit counter, while for checking before work, do-while when one body entry is needed, and range-based for for elements. Choose readable control flow instead of memorising a known-count versus unknown-count rule.

Now sum the even values in {3,4,7,8} with a range-based loop, using continue to skip odd values. Expect 12: the total moves 0 -> 4 -> 12. Then try an indexed version.

For an optional structured next step, explore the Coding for Placements course.