for Loop in C++
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.
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).
Scope the counter
Declaring int i inside the header confines it to the loop; it cannot leak out and collide with later code.
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.
Empty slots are legal
for (;;) loops forever (condition defaults to true) — pair it with a break, or fill all three slots for clarity.
#include <iostream> int main() { int sum = 0; for (int i = 1; i <= 5; ++i) { sum += i; } std::cout << sum << std::endl; return 0;}One pass over n iterations with constant extra state.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.