Skip to content
Loops
step 1/5

Reading — step 1 of 5

Learn

~3 min readControl Flow

Loops

C++ inherits C's three loops and adds the one you'll use most: the range-based for, which walks a container without index bookkeeping — and therefore without index bugs. Learn all four shapes and, more importantly, the instinct for which one a problem wants.

The classic three

for (int i = 1; i <= n; i++) {      // counted
    sum += i;
}

while (n > 1) {                     // condition-driven; may run zero times
    n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
}

do {                                // always runs at least once
    std::cin >> choice;
} while (choice != 0);

Same grammar as C, same disciplines: i < n walks indices 0…n−1, i <= n counts 1…n — choose consciously; a stray semicolon after for (…) or while (…) is a silent empty body (-Wall catches it); break exits the loop, continue skips to the next pass, while (true) + break is the idiomatic run-forever.

Range-based for: the modern default

std::string s = "hello";
for (char c : s) {                  // every char, in order, no indices
    std::cout << c << ' ';
}

std::vector<int> v = {10, 20, 30};  // next lesson's star, previewed
for (int x : v) {
    sum += x;
}

Read for (char c : s) as "for each char c in s." No off-by-one possible, no size() in sight. Two refinements that make it production-grade:

for (int& x : v)  { x *= 2; }       // & — REFERENCE: modify the real elements
for (const auto& x : v) { … }       // read-only, no copies — the default idiom

Without &, each x is a copy — mutations vanish (the same copy rule as every value in C++). auto asks the compiler to deduce the type — universally used in range-fors. The full pattern const auto& ("read each element, don't copy it") is what you'll see in every modern codebase; adopt it now and your loops are already idiomatic.

When do you still index? When the index itself matters (comparing v[i] to v[i+1], printing positions) — the classic for isn't legacy, it's the tool for index-shaped problems. Everything else: range-for.

Your exercise: Sum 1 to N

Read n, print 1 + 2 + … + n. The accumulator:

int n;
std::cin >> n;
long long total = 0;
for (int i = 1; i <= n; i++) {
    total += i;
}
std::cout << total << "\n";

The three graded details are old friends by now if you've walked other tracks — and worth engraving if this is your first: total initialized to 0 before the loop; <= because the sum includes n itself; long long because n(n+1)/2 outruns int near n ≈ 65,000 and signed overflow in C++ is undefined behavior, not a wraparound you can reason about. Counted loop, inclusive bound, wide accumulator — the pattern behind half the exercises that follow.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…