Explain it simply
Explain it simply
A for loop is C's way of saying "do this five times". It is like counting push-ups at the gym: start at 1, keep going until you reach 5, add one after each push-up. All three rules sit together on the first line of the loop, so a reader can tell at a glance how many times it runs.
Pick for whenever the count is known before the loop starts: visiting each item, printing rows, retrying a fixed number of times.
Problem → Why → Solution
The problem: a countdown that never reaches the end
Say you want to print indexes backwards, counting from 2 down to 0. With int that works. But C usually stores sizes and indexes in size_t, an unsigned type, and the loop below never ends. After printing 2, 1 and 0 it prints 18446744073709551615 on a 64-bit system and keeps counting down from there.
#include <stdio.h>
int main(void) {
size_t count = 3;
for (size_t i = count - 1; i >= 0; i--) { /* i >= 0 is ALWAYS true */
printf("index %zu\n", i);
}
return 0;
}Why does it not stop?
size_t is unsigned, so its smallest value is 0. Decrementing 0 does not give -1; it wraps around to the largest value, SIZE_MAX. That means i >= 0 can never be false. GCC knows this: with -Wextra it reports "comparison of unsigned expression in '>= 0' is always true [-Wtype-limits]". Plain gcc and even -Wall stay silent, which is why -Wextra belongs in your build command.
Core concept: three parts in one header
A for loop is a while loop with its three parts gathered into one header: for (init; condition; update). The init runs exactly once, before anything else. Then C repeats a fixed cycle: test the condition, run the body if it is true, run the update, test again. The update always runs after the body, never before it, so in for (int i = 1; i <= 5; i++) the body first sees i == 1 and the last pass sees i == 5.
Because all the loop control sits on one line, you can answer "how many times?" without hunting through the body. Since C99 the loop variable can be declared inside the header (int i = 0). It then exists only inside the loop, so a second loop can reuse the name i, and code after the loop cannot accidentally use a stale counter.
Counting from 0 with a strict less-than, for (int i = 0; i < n; i++), runs exactly n times and visits indexes 0 to n - 1, which matches how C arrays are numbered (see the Arrays lesson). Counting from 1 with <=, as in the Step example, also runs n times and suits numbers meant for display. Mixing the two, starting at 0 but testing with <=, gives n + 1 passes: the off-by-one error behind many out-of-bounds bugs.
Any of the three parts may be empty. for (;;) has no condition, which C treats as always true, so it is an endless loop like while (1). The update does not have to be ++: i += 2 counts in twos and i-- counts down. Take care when counting down with an unsigned type such as size_t, the type C uses for sizes and array lengths, because an unsigned value can never become negative.
The order of a for loop
-----------------------
for ( init ; condition ; update ) { body }
(1) init ----> (2) condition? --false--> statement after the loop
| ^
true |
v |
(3) body |
| |
v |
(4) update-+- Run init exactly once
- Test the condition (false: leave)
- Run the body
- Run the update, back to the test
The update runs after the body, so the first value the body sees is exactly the one init set.
General pattern
for (type counter = start; counter < limit; counter++) {
statements;
}
for (type counter = start; counter > stop; counter -= step) {
statements;
}
for (;;) { /* no condition: loops until break or return */
statements;
}The two semicolons inside the header separate the three parts. A counter declared in the header is visible only inside the loop. The update can be ++, --, += step or any other expression.
Example: counting up, in steps and down
Three loops show three header shapes. The first prints steps 1 to 5, the second adds up the even numbers from 2 to 10, and the third counts down from 3. Notice that the third loop reuses the name i.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) {
printf("Step %d\n", i);
}
int sum = 0;
for (int n = 2; n <= 10; n += 2) {
sum += n;
}
printf("Sum of even numbers 2..10: %d\n", sum);
for (int i = 3; i > 0; i--) {
printf("%d... ", i);
}
printf("Go!\n");
return 0;
}Code breakdown
- Counting up
for (int i = 1; i <= 5; i++) {i starts at 1 and the body runs for 1, 2, 3, 4 and 5. When i becomes 6, 6 <= 5 is false and the loop ends: exactly five passes.
- Counting in steps
for (int n = 2; n <= 10; n += 2) {The update is n += 2 instead of ++, so n takes the values 2, 4, 6, 8 and 10. The odd numbers are skipped without any if.
- Accumulator outside the loop
sum += n;sum is declared outside the loop, so it survives every pass and builds up to 30. Declared inside the body, it would restart at 0 on each pass.
- Counting down, reusing i
for (int i = 3; i > 0; i--) {The first loop's i disappeared when that loop ended, so a fresh i can be declared here. i > 0 leaves out 0, so only 3, 2 and 1 are printed.
- After the loop
printf("Go!\n");The printf calls inside the loop have no \n, so 3... 2... 1... share one line; this statement runs once, after the loop, and finishes that line.
Step 1
Step 2
Step 3
Step 4
Step 5
Sum of even numbers 2..10: 30
3... 2... 1... Go!for and while are the same loop
Every for loop can be rewritten as a while loop: move the init before the loop and the update to the end of the body. Only two differences remain. A variable declared in the header lives only inside the loop, and continue (next lesson) still runs a for loop's update, whereas in a while loop it skips an update written at the end of the body.
#include <stdio.h>
int main(void) {
int i = 0; /* init */
while (i < 3) { /* condition */
printf("while: %d\n", i);
i++; /* update */
}
for (int j = 0; j < 3; j++) { /* the same three parts, one line */
printf("for: %d\n", j);
}
return 0;
}Counting down safely with size_t
To fix the loop from the problem section, test before you decrement. i-- > 0 compares the current value of i with 0 and only then subtracts one. With count equal to 3 the body sees 2, 1 and 0; when i is 0 the test fails, so the wrapped-around value never reaches the body. If count is 0, the body never runs at all.
#include <stdio.h>
int main(void) {
size_t count = 3;
/* i-- > 0 tests first, then decrements: the body sees 2, 1, 0 */
for (size_t i = count; i-- > 0; ) {
printf("index %zu\n", i);
}
return 0;
}Loops inside loops
A for loop's body can contain another for loop. For every single pass of the outer loop, the inner loop runs from start to finish. Below, the inner condition depends on the outer row, so each row gets one more star and a triangle appears. The total number of inner passes is the sum over all outer passes, here 1 + 2 + 3 + 4 = 10.
#include <stdio.h>
int main(void) {
for (int row = 1; row <= 4; row++) {
for (int star = 0; star < row; star++) {
printf("*");
}
printf("\n");
}
return 0;
}In real projects
Where this shows up in real projects
Counting loops are the workhorse of C code. You find them computing a checksum over every byte of a buffer, visiting every pixel of an image with nested row and column loops, averaging an array of sensor readings, and retrying a network request a limited number of times with for (int attempt = 1; attempt <= 3; attempt++).
In code review, the loop header is one of the first places reviewers check, because the bound decides whether a loop touches memory it does not own. Many teams compile with -Wall -Wextra -Werror in CI, so a -Wsign-compare warning about an int compared with a size_t in a loop header ("comparison of integer expressions of different signedness") fails the build instead of shipping.
Common mistakes
Common mistakes
1. Starting at 0 and testing with <=
for (int i = 0; i <= n; i++) runs n + 1 times, not n. When i is an array index, the last pass reads or writes one element past the end, which is undefined behaviour. Remember: start at 0, test with <.
2. A semicolon right after the header
for (k = 0; k < 5; k++); runs an empty body five times, then runs the block below once: with k declared outside, you get a single line "k = 5". If k is declared in the header instead, the block can no longer see it and you get an 'k' undeclared compile error. -Wall can also warn with -Wmisleading-indentation.
3. Changing the counter inside the body as well
With i++ already in the header, another i++ in the body moves two steps per pass and silently skips half the values. Let the header be the only place that changes the counter; if you need to skip an item, use continue.
4. Mixing an int counter with a size_t limit
In i < count with i an int and count a size_t, i is converted to unsigned before the comparison, so a negative value turns into a huge number. -Wextra reports it as -Wsign-compare. Give the counter the same type as the limit (size_t i).
Best practices
Best practices
- Declare the loop variable in the header so it cannot leak out of the loop.
- Use i = 0; i < count as the standard index loop, and give the counter the same type as the limit.
- Count down over size_t with i-- > 0, never with i >= 0.
- Give nested loop counters meaningful names such as row and col; swapping i and j is a classic bug.
Mini challenge
Mini challenge: a times table
Use two nested for loops to print a times table with 4 rows and 5 columns. Every cell is row * col, and after the loops finish, print the total of all the cells.
- The outer loop counts row from 1 to 4, the inner loop counts col from 1 to 5
- Print each cell with "%4d" so the columns line up
- End every row with a newline
- Add every cell to a running total and finish with "Grand total: ..."
#include <stdio.h>
int main(void) {
// TODO: a running total for every cell
// TODO: outer loop: row from 1 to 4
// TODO: inner loop: col from 1 to 5
// print row * col with "%4d" and add it to the total
// TODO: end the row with a newline
// TODO: print "Grand total: <total>"
return 0;
}Expected: The program prints this table and total: 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 Grand total: 150
Show hint
Put the newline between the inner loop's closing brace and the outer loop's closing brace, so it runs once per row. Declare the total outside both loops.
Show solution
#include <stdio.h>
int main(void) {
int grand_total = 0;
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= 5; col++) {
int cell = row * col;
printf("%4d", cell);
grand_total += cell;
}
printf("\n");
}
printf("Grand total: %d\n", grand_total);
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- In for (init; condition; update), init runs once, then test, body and update repeat in that order.
- i = 0; i < n runs exactly n times; mixing 0 with <= is the classic off-by-one error.
- A variable declared in the header exists only inside the loop.
- Count down over size_t with i-- > 0, because i >= 0 is always true for an unsigned value.
GNU C compiler diagnostics — GNU Project