Learn C
#include "controlflow/for_loop.h"

for Loop in C

#concept

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.

#how it works
1

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).

2

Declare in the header (C99+)

for (int i = 0; ...) confines i to the loop; under C89 rules, declare int i; above the loop instead.

3

Stepping and bounds

i += 2 strides by twos, i-- counts down; i < n (not <=) matches zero-based arrays and dodges off-by-one.

4

Empty slots are legal

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

#example
#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;
}
Output
15
1i declared C89-style above the loop; iterations run 1 through 5.
2Each pass adds the current i — 1+2+3+4+5 accumulates into sum.
315 prints once the condition fails past 5.
#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 loops
Stepped sequences (evens, reverse) via custom init/step
Fixed-iteration protocols and retry loops with bounded attempts

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.