for Loop in C
The classic for loop packs initialization, condition, and step into one header: for (i = 0; i < n; ++i). It is the precision tool for counted repetition — array traversal, fixed iterations, stepped sequences — with everything controlling the loop in one visible line.
C99 allows declarations inside the header (for (int i = 0; ...)), scoping the counter to the loop; C89 requires declaring before it. Prefer prefix ++i, half-open bounds (i < n) matching zero-based indexing, and size_t counters when bounding by sizes.
Three slots, one line
Init runs once, the condition tests before every iteration, the step runs after each body — for (i = 0; i < 5; ++i).
Declare in the header (C99+)
for (int i = 0; ...) confines i to the loop; under C89 rules, declare int i; above the loop instead.
Stepping and bounds
i += 2 strides by twos, i-- counts down; i < n (not <=) matches zero-based arrays and dodges off-by-one.
Empty slots are legal
for (;;) loops forever — pair it with a break, or fill all three slots for clarity.
#include <stdio.h> int main(void) { int sum = 0; int i; for (i = 1; i <= 5; ++i) { sum += i; } printf("%d\n", sum); 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.