InfoCode

C++ · Control structures

Loop structures

Compare C++ for, while and do-while loops with execution order, sum and sentinel examples, and common boundary mistakes.

Written by InfoCode · Technical references below

Practice this topic in the app Read the lesson in the app

How for, while and do-while execute

If you want to output 1 to 100, would you have to write 100 lines of cout? Of course not—loops help us repeat execution!

for loop (most commonly used when the number of repetitions is known):

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

Execution order: ① initialization (executed only once) → ② check the condition → ③ execute the loop body → ④ execute the update → return to ②, until the condition is false.

while loop (when the number of repetitions is uncertain, continue as long as the condition holds):

while (condition) {
    // loop body
}

while checks the condition first, then executes. If the condition is false from the start, it does not execute even once.

break immediately exits the loop; continue skips the remaining code of the current iteration and proceeds to the next iteration.

do-while:do { loop body } while (condition); executes once first and then checks, so even if the initial condition is false it still runs once, and the semicolon at the end cannot be omitted. It is suitable for processes that must be attempted at least once, for example when splitting a non-negative integer into digits, the number zero must also be handled as one digit.

For vs while: compare the same task

To sum 1 through 5, a for groups initialization, condition and update; a while writes them separately. Both check before executing, so the body can run zero times. A do-while executes once before checking.

int sum = 0;
for (int i = 1; i <= 5; ++i) sum += i;

int total = 0, j = 1;
while (j <= 5) { total += j; ++j; }

Both results are 15. A for loop often reads clearly for a known counting range; a while loop often reads clearly when waiting for a sentinel. Neither syntax is inherently faster. In a for loop, continue still leads to the update; check for missed updates when rewriting it as while.

Check your understanding: If the condition becomes i < 5, what is the sum, and why is one iteration missing?

The sum is 10: only 1, 2, 3 and 4 are added; the condition is false at 5.

What happens after skipping 3?

Add 1 through 5, but skip 3. Predict the final sum before tracing each iteration. A for loop updates at the end of each iteration. After continue skips the remaining body, the update still runs before the condition is checked.

Current iActionsumi after update
1Add 112
2Add 233
3continue; do not add34
4Add 475
5Add 5126

Next, 6 <= 5 is false and the loop ends. First common error: a semicolon immediately after the for parentheses creates an empty loop body; indentation does not put later statements inside it. Second: a while loop with its update at the end can stay on the same value if continue skips that update. Check that every path advances or exits.

A for loop often suits a known count, and a while loop often suits a changing condition. This is a readability choice, not a syntax restriction or a speed guarantee. n repetitions of constant work take O(n); analyze nested loops and early exits by their actual execution counts.

Run and check: continue still reaches the for update

#include <iostream>
int main() {
    int sum = 0;
    for (int i = 1; i <= 5; ++i) {
        if (i == 3) { continue; }
        sum += i;
    }
    std::cout << sum << "\n";
}

Skipping 3 gives 1+2+4+5=12. The loop finishes when its condition becomes false.

Try before revealing each answer

Starting at i=1, how many iterations run if the upper bound is 0?

Zero. The first condition 1 <= 0 is false, so sum stays 0.

What happens if a while body continues at i==3 before reaching ++i at its end?

With no other update or exit, i stays at 3. If the condition remains true, the loop cannot finish. Identify the stuck state without running an infinite loop.

To skip one unsuitable item but keep checking later items, use break or continue?

Use continue and ensure the loop still advances. break exits the nearest enclosing loop.

Sum, sentinel and loop-boundary examples

Example 1: for loop outputs the sum of 1 to 5

#include <iostream>
using namespace std;
int main() {
    int sum = 0;
    for (int i = 1; i <= 5; i++) {
        sum += i;
    }
    cout << sum << endl; // output 15
    return 0;
}

i increases from 1 to 5, and each time i is added to sum: 0+1+2+3+4+5=15; after the loop ends, output 15.

Example 2: while loop keeps reading until 0

#include <iostream>
using namespace std;
int main() {
    int n, sum = 0;
    cin >> n;
    while (n != 0) {
        sum += n;
        cin >> n;
    }
    cout << sum << endl;
    return 0;
}

Input 3 5 2 0; the program accumulates 3, 5, and 2, exits the loop when it reads 0, and outputs 10.

Example 3: zero also has one digit

#include <iostream>
using namespace std;
int main() {
    int n = 0, digits = 0;
    do { ++digits; n /= 10; } while (n != 0);
    cout << digits << endl;
}

Output 1. If you directly use while(n!=0), when the initial n is zero it does not execute even once, and it would incorrectly judge that zero has zero digits.

Tips

Prerequisites

Technical references

Scope note

This lesson is written by InfoCode and is not an official syllabus; the reference level is a site mapping and does not represent official levels, certification or eligibility. Practice records do not establish mastery or eligibility.

Reference level: GESP Level 1 (site mapping)

See contest pathways