Learn C++
#include "controlflow/for_loop.hpp"

for Loop in C++

//concept

The classic for loop packs initialization, condition, and step into one header: for (int i = 0; i < n; ++i). It is the precision tool for counted repetition — array traversal, fixed iterations, stepped sequences — because everything controlling the loop sits in one visible line.

Prefer prefix ++i (no discarded copy semantics to think about), keep the counter scoped inside the header so it dies with the loop, and use std::size_t for container bounds to dodge signed/unsigned warnings. Any of the three header slots may be empty, but an empty condition means infinite.

//how it works
1

Three slots, one line

Init runs once, the condition is tested before every iteration, and the step runs after each body — for (int i = 0; i < 5; ++i).

2

Scope the counter

Declaring int i inside the header confines it to the loop; it cannot leak out and collide with later code.

3

Stepping and bounds

i += 2 strides by twos, i-- counts down; half-open bounds (i < n) match zero-based indexing and off-by-one-proof the loop.

4

Empty slots are legal

for (;;) loops forever (condition defaults to true) — pair it with a break, or fill all three slots for clarity.

//example
#include <iostream>
 
int main() {
int sum = 0;
for (int i = 1; i <= 5; ++i) {
sum += i;
}
std::cout << sum << std::endl;
return 0;
}
Output
15
1i starts at 1; the loop runs while i <= 5, stepping by one each round — five iterations total.
2Each pass adds the current i (1, then 2, ... 5) into sum.
3After i passes 5 the condition fails and 1+2+3+4+5 = 15 prints.
//complexity
time O(n)
space O(1)

One pass over n iterations with constant extra state.

//use cases
Summing, counting, and scanning arrays element by element
Times-table and matrix traversals with nested for loops
Stepped sequences (even numbers, reverse order) via custom steps
Fixed-iteration simulations like game ticks and numeric methods

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.