Menu

C++ For Loop: Syntax, Examples, and Common Mistakes

How to repeat code with the C++ for loop - the three-part header, counting up and down, looping over arrays, nesting, break and continue, and the off-by-one and unsigned bugs that bite everyone.

This page includes runnable editors - edit, run, and see output instantly.

Why a for Loop

A switch picks one branch to run once. But real programs need to do something repeatedly: print every score, sum a list of numbers, draw 10 rows of a grid. The for loop is C++'s workhorse for repeating code a known number of times, with a built-in counter you control.

Everything a for loop needs lives in one compact header, so the whole "how many times and how" story is visible at a glance.

The Three-Part Header

A for loop header has three parts separated by semicolons: an initializer, a condition, and an update.

for (initializer; condition; update) {
    // body - runs while condition is true
}

They execute in a specific order: the initializer runs once at the start; then the condition is checked before every iteration; the body runs only if the condition is true; and the update runs at the end of each iteration, just before the condition is checked again.

Here int i = 0 runs once. Then i < 5 is checked: while it holds, the body prints and i++ bumps the counter. When i reaches 5 the condition is false, so the loop exits and done prints. The body runs exactly 5 times, with i taking the values 0 through 4.

Declaring the counter inside the header (int i = 0) keeps i scoped to the loop - it does not exist after the closing brace, which is exactly what you want.

Counting Up, Down, and by Steps

The update part is not limited to i++. You can count down, step by any amount, or loop over an array index.

The first loop runs while i > 0, decrementing each time, so it prints 5 4 3 2 1. The second adds 2 each pass and uses <= 10 because 10 is a value we want to include. Match your condition to your update: counting down pairs with > or >=, counting up with < or <=.

Looping Over an Array

The most common use of a counting loop is walking an array by index. The counter doubles as the position you read.

Note the condition is i < n, not i <= n. A 5-element array has valid indices 0 through 4; index 5 is past the end. Reading scores[5] is undefined behavior - it might print garbage, crash, or appear to work and corrupt memory silently. The i < n pattern is the safe default for any zero-based array.

If you only need the values and not the index, a range-based for is cleaner. Reach for the classic indexed loop when you actually need the position.

break and continue

Two keywords let you change the flow mid-loop. break exits the loop immediately; continue skips the rest of the current iteration and jumps to the update.

The first loop stops the moment it finds 7 and never checks the rest. The second uses continue to skip the body's print whenever i is even - the update i++ still runs, so the loop keeps advancing. A subtle gotcha: continue jumps to the update, so if you ever rely on continue inside a loop whose counter is updated inside the body rather than the header, you can accidentally skip that update and spin forever.

Nested Loops

Put one for inside another to work with grids, tables, or pairs. The inner loop runs completely for each single step of the outer loop.

This prints a 3x3 multiplication grid. The outer loop fixes a row, the inner loop sweeps every col for that row, then a newline ends the row. Give the counters distinct names (row/col, not i/i) - reusing one name shadows the outer and produces baffling bugs. Watch the cost too: nesting an n-loop inside an n-loop runs the body n * n times, which adds up fast.

Common Gotchas

A few traps account for most for-loop bugs in C++:

  • Off-by-one: i <= n with a zero-based size reads one element past the end. Use i < n.
  • Unsigned underflow: counting down with an unsigned type never goes negative. for (size_t i = n - 1; i >= 0; i--) loops forever, because i >= 0 is always true for an unsigned value - when i is 0, i-- wraps to a huge positive number. Use a signed int for downward counts, or rewrite the condition.
  • Modifying the counter inside the body: changing i in the body as well as the header makes the loop count unpredictable. Pick one place.
// BUG: infinite loop - unsigned i is never < 0
for (size_t i = n - 1; i >= 0; i--) {
    process(arr[i]);
}

Floating-point counters are another quiet hazard: for (double x = 0.0; x != 1.0; x += 0.1) may never hit exactly 1.0 because 0.1 cannot be stored precisely. Loop with an integer count and compute the value inside, or use < instead of !=.

Next: while Loops

The for loop shines when you know the count up front. But sometimes you need to repeat until a condition changes - read input until end-of-file, retry until success - without a fixed number of steps. That is the job of the while loop, which strips the header down to just a condition. It is the next page.

Frequently Asked Questions

How do you write a for loop in C++?

Put three parts in the header separated by semicolons: an initializer, a condition, and an update. for (int i = 0; i < 5; i++) { cout << i; } runs the body with i going 0, 1, 2, 3, 4. The loop stops as soon as the condition becomes false.

What is the difference between a for loop and a range-based for loop in C++?

A classic for gives you an index counter you control (for (int i = 0; i < n; i++)), which you need when you want the position or want to step in a custom way. A range-based for (for (int x : v)) hides the index and just hands you each element - cleaner when you only need the values.

Why does my C++ for loop run one too many or one too few times?

That is the classic off-by-one bug. Using <= instead of < with a zero-based size runs one extra iteration and reads past the end of the array; using < when you meant to include the last value runs one short. For an array of size n, the safe pattern is for (int i = 0; i < n; i++).

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED