The Analogy: The Numbered Seats
A while loop is "keep going until something happens". A for loop is a theatre usher walking a row of numbered seats: start at seat 1, stop after seat 30, move one seat each time. Everything about the journey is declared in a single line at the top, so a reader can see the whole shape of the loop without hunting through the body.
That is why for is the most common loop in C++. When you know where you start, where you stop and how you step, putting all three in the header means there is nowhere for an off-by-one to hide.
Syntax or Core Structure
#include <iostream>
#include <vector>
#include <string>
int main() {
// for (initialisation; condition; update)
for (int i = 0; i < 5; ++i) {
std::cout << i << " "; // 0 1 2 3 4
}
std::cout << "\n";
// Counting down
for (int i = 5; i > 0; --i) {
std::cout << i << " "; // 5 4 3 2 1
}
std::cout << "\n";
// Any step you like
for (int i = 0; i <= 20; i += 5) {
std::cout << i << " "; // 0 5 10 15 20
}
std::cout << "\n";
// Two counters moving in opposite directions
for (int lo = 0, hi = 9; lo < hi; ++lo, --hi) {
std::cout << lo << "-" << hi << " ";
}
std::cout << "\n";
// Range-based for (C++11): the modern default for containers
const std::vector<std::string> names{"Ada", "Alan", "Grace"};
for (const std::string& name : names) {
std::cout << name << " ";
}
std::cout << "\n";
return 0;
}
The order of operations is: initialise once, then test, body, update, test, body, update... The test happens before the first pass, so for (int i = 0; i < 0; ++i) runs zero times.
Technical Depth: Off-By-One, Signedness and the Range-Based Form
< versus <= decides everything
const int size{5};
int data[size]{10, 20, 30, 40, 50};
for (int i = 0; i < size; ++i) { std::cout << data[i]; } // correct: 0..4
for (int i = 0; i <= size; ++i) { std::cout << data[i]; } // BUG: reads data[5]
for (int i = 1; i < size; ++i) { std::cout << data[i]; } // BUG: skips data[0]
Indices run 0 to size - 1, so the canonical loop is i = 0; i < size; ++i. Reading data[5] is undefined behaviour: it may print rubbish, may crash, may silently corrupt an adjacent variable. Nothing in the language stops you — this is precisely the freedom C++ trades for speed.
The signed/unsigned warning
std::vector<int> v{1, 2, 3};
for (int i = 0; i < v.size(); ++i) { } // WARNING: signed vs unsigned
for (std::size_t i = 0; i < v.size(); ++i) { } // correct type
for (std::size_t i = v.size(); i-- > 0; ) { } // safe reverse idiom
for (std::size_t i = v.size() - 1; i >= 0; --i) { } // INFINITE: unsigned never < 0
v.size() returns an unsigned std::size_t. Comparing it with an int makes the compiler convert one side, which -Wall warns about. The reverse loop is the real trap: an unsigned counter can never go below zero, so i >= 0 is always true. The i-- > 0 form works because it tests the old value and then decrements — worth memorising.
Scope, and modifying the counter
for (int i = 0; i < 5; ++i) { }
// std::cout << i; // ERROR: i died with the loop -- this is good
int found = -1;
for (int i = 0; i < 5; ++i) {
if (data[i] == 30) { found = i; break; } // export the value deliberately
}
for (int i = 0; i < 10; ++i) {
i += 2; // legal but confusing: the step is now in two places
}
Declaring the counter in the header confines it to the loop, which prevents accidental reuse. When you need the value afterwards, copy it into a variable declared outside — that makes the intent explicit. Changing the counter inside the body is legal but hides the step from the header; if you need that, use while.
The range-based for, and the ampersand that matters
std::vector<int> nums{1, 2, 3};
for (int n : nums) { n *= 2; } // COPIES each element -- nums unchanged
for (int& n : nums) { n *= 2; } // reference -- nums becomes {2, 4, 6}
for (const auto& n : nums){ std::cout << n; } // read-only, no copy: the default
// With an index, when you need one (C++20 has better options)
for (std::size_t i = 0; i < nums.size(); ++i) {
std::cout << i << ":" << nums[i] << " ";
}
const auto& is the right default for reading: it avoids copying (which matters enormously for strings and objects) and stops you modifying by accident. Use auto& to modify in place. Use plain auto only for cheap types you intend to copy.
One hazard: never add or remove elements from a container while range-looping over it. Doing so can invalidate the internal iterator and the loop reads freed memory.
Structure of a nested loop
for (int row = 1; row <= 3; ++row) {
for (int col = 1; col <= 3; ++col) {
std::cout << row * col << "\t";
}
std::cout << "\n";
}
The inner loop restarts completely on every outer pass, so the total number of body executions is the product: 3 x 3 = 9. That multiplication is why nested loops over large data get slow fast — two nested loops over a million items is a million million operations.
Loop forms compared
| Form | Use when |
|---|---|
for (int i = 0; i < n; ++i) | you need the index, or a plain count |
for (const auto& x : c) | reading every element of a container |
for (auto& x : c) | modifying every element in place |
for (auto i = c.size(); i-- > 0; ) | walking backwards safely |
while | the number of passes is genuinely unknown |
Real World Example: A Sales Report
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
int main() {
const std::vector<std::string> months{"Jan", "Feb", "Mar", "Apr"};
std::vector<double> sales{1250.00, 980.50, 1710.25, 1425.75};
// 1. Aggregate: index loop because we need to pair two containers
double total{0.0};
double best{sales[0]};
std::size_t bestIndex{0};
for (std::size_t i = 0; i < sales.size(); ++i) {
total += sales[i];
if (sales[i] > best) {
best = sales[i];
bestIndex = i;
}
}
const double average = total / static_cast<double>(sales.size());
// 2. Report: range-based, read-only, no copies
std::cout << std::fixed << std::setprecision(2);
for (std::size_t i = 0; i < months.size(); ++i) {
std::cout << months[i] << " " << std::setw(8) << sales[i];
// 3. Nested loop draws a bar, one block per 200 units
const int blocks = static_cast<int>(sales[i] / 200.0);
std::cout << " ";
for (int b = 0; b < blocks; ++b) {
std::cout << "#";
}
std::cout << "\n";
}
// 4. Modify in place: apply a 10% uplift to every month
for (double& amount : sales) {
amount *= 1.10;
}
std::cout << "\nTotal: " << total << "\n";
std::cout << "Average: " << average << "\n";
std::cout << "Best: " << months[bestIndex] << " (" << best << ")\n";
std::cout << "After uplift, Jan is " << sales[0] << "\n";
return 0;
}
Each loop uses the form that fits its job. The aggregate loop needs an index because it records which month was best, and it uses std::size_t to match size(). The report loop also needs the index to read two parallel containers at once. The bar chart is a nested loop whose inner count is computed per row rather than fixed. And the uplift uses double& because it must change the stored values — with plain double it would double copies and leave sales untouched. Note static_cast<double> on the average: dividing by an unsigned size() without it would drag the whole expression into integer territory.
Common Mistakes
i <= sizeinstead ofi < size. Reads one element past the end — undefined behaviour.- A reverse loop with an unsigned counter:
for (std::size_t i = n - 1; i >= 0; --i)never ends. - A semicolon after the header:
for (int i = 0; i < 5; ++i);gives an empty body. - Comparing
intwith.size()and ignoring the warning. for (auto x : container)when the elements are strings or objects — a silent copy per pass.- Forgetting
&when you meant to modify elements; the loop appears to do nothing. - Adding or erasing elements while range-looping over the same container.
- Calling an expensive function in the condition:
i < computeLimit()may run every single pass. Hoist it into aconstbefore the loop.
Best Practices
- Prefer the range-based
forwhenever you do not need the index. - Use
const auto&for reading,auto&for writing, and plainautoonly for cheap copies. - Declare the counter in the header so it cannot leak or be reused.
- Match the counter type to what you compare against —
std::size_tagainst.size(). - Use
++irather thani++. Identical for integers, cheaper for iterators, and consistent. - Keep the body short. If it grows past roughly fifteen lines, extract a function.
- Consider the standard algorithms.
std::accumulate,std::find,std::count_ifandstd::sortfrom<algorithm>and<numeric>replace many hand-written loops with one clear line.
Practice Exercises
- Times table: Print a formatted 1–12 multiplication grid with aligned columns using nested
forloops andstd::setw. - Two ways to reverse: Print a
std::vector<int>backwards, once with an index loop and once with thei-- > 0idiom onstd::size_t. Explain in a comment why the naivei >= 0version hangs. - Primes to 100: Use a nested
forwithbreakto print every prime below 100, then optimise the inner loop to stop at the square root and count how many fewer checks it performs. - The step that never lands: Write a
forloop that walks from0.0to1.0in steps of0.1usingdouble iandi != 1.0as the condition, and watch it run past the end. Fix it two ways — once by looping over an integer count and multiplying, once by comparing with a tolerance — then print each accumulated value withstd::setprecision(17)and explain in a comment which fix you would put in production code.