Skip to content

Module 2 · Variables, Operators and Control Flow — topic 4 of 4

Loops

while, do-while, the counting for loop and the range-based for loop, plus break and continue and how to avoid off-by-one errors.

Beginner 14 min read·Lesson 7 of 40 in C++ Programming

Learning objectives

  • Choose between while, do-while, for and range-for
  • Iterate containers safely with range-for
  • Use break and continue correctly

Definition

Iteration statements repeat a statement while a condition holds. The range-based for loop (C++11) iterates over every element of an array, container or initializer list.

Introduction

C++ has C's three loops plus the range-based for, which removes index arithmetic entirely when you just need each element.

The loop variable of a range-for can be a copy, a reference (to modify elements) or a const reference (to read large elements without copying).

Why it matters

Most bugs in array processing are index mistakes; range-for eliminates them.

Loops are where programs spend their time; knowing which loop fits each task makes code clearer.

Detailed explanation

while (cond) tests first; do { } while (cond); runs at least once; for (init; cond; step) gathers the three parts of a counting loop.

for (auto x : v) copies each element; for (auto& x : v) lets you modify elements; for (const auto& x : v) reads without copying.

break leaves the innermost loop; continue jumps to the next iteration.

Use std::size_t (or range-for) when comparing with size() to avoid signed/unsigned warnings.

Syntax

C++
for (int i = 0; i < n; ++i) { /* counting */ }
for (const auto& item : items) { /* each element */ }
while (std::cin >> x) { /* until input ends */ }
do { /* at least once */ } while (again);
  • i < n from 0 gives exactly n iterations.
  • Use auto& to modify container elements.
  • Reading in the condition stops at end of input.

Code examples

Range-for to modify elements

C++
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3, 4};
for (int& x : v) x *= 10;
for (int x : v) std::cout << x << ' ';
std::cout << '\n';
return 0;
}
Output
10 20 30 40

Sum until input ends

C++
#include <iostream>
int main() {
int x, sum = 0, n = 0;
while (std::cin >> x) { sum += x; ++n; }
std::cout << n << " numbers, sum " << sum << '\n';
return 0;
}
Input
4 8 15 16 23 42
Output
6 numbers, sum 108

More examples

Primes with nested loops, break and continue

C++
#include <iostream>
#include <vector>
int main() {
std::vector<int> primes;
for (int n = 2; primes.size() < 10; ++n) {
bool prime = true;
for (int d = 2; d * d <= n; ++d)
if (n % d == 0) { prime = false; break; }
if (!prime) continue;
primes.push_back(n);
}
for (const auto& p : primes) std::cout << p << ' ';
std::cout << '\n';
return 0;
}
Output
2 3 5 7 11 13 17 19 23 29

Step-by-step explanation

  • The outer loop keeps testing numbers until ten primes are collected.
  • The inner loop tries divisors up to √n and breaks at the first one.
  • continue skips non-primes.
  • The range-for prints the vector.

Expected output

Running “Primes with nested loops, break and continue” prints exactly:

TextOutput
2 3 5 7 11 13 17 19 23 29

Practical applications

  • Servers loop reading requests until shutdown.
  • Data processing iterates containers with range-for.
  • Simulations loop over time steps.

Best practices

  • Prefer range-for when you don't need the index.
  • Use const auto& for large elements.
  • Keep loop bodies short; move work into functions.

Common mistakes

Copying in range-for when you meant to modify

Avoid

for (auto x : v) x = 0;

Prefer

for (auto& x : v) x = 0;

Without &, x is a copy and the vector is unchanged.

Modifying a vector while iterating it

Avoid

for (auto x : v) if (x < 0) v.push_back(0);

Prefer

std::vector<int> extra;
for (auto x : v) if (x < 0) extra.push_back(0);
v.insert(v.end(), extra.begin(), extra.end());

push_back can reallocate and invalidate the iterators the loop uses — undefined behaviour.

Important notes

  • C++20 ranges allow loops like for (int i : std::views::iota(0, 10)).
  • An infinite loop without observable side effects can be assumed to terminate by the compiler; always make progress.

Key takeaways

  • Range-for iterates every element; use & to modify.
  • do-while runs at least once.
  • Don't change a container's size while range-iterating it.

Try it yourself

  1. 1
    Print the multiplication table of n using a for loop.
  2. 2
    Read words until end of input and print the longest one.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

7 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this topic