A for loop in C repeats a statement while a condition is true: for (init; condition; update) statement. The classic form, for (int i = 0; i < 5; ++i), runs the body five times with i set to 0 through 4.
#include <stdio.h>
int main(void)
{
for (int i = 1; i <= 5; ++i) {
printf("%d ", i);
}
printf("\n");
return 0;
}
Example output:
1 2 3 4 5
How the for loop in C works
The statement has three clauses separated by semicolons, followed by the loop body:
for (init-clause; cond-expression; iteration-expression)
loop-statement
The order of events is fixed:
- The init clause runs once, before anything else.
- The condition is evaluated. If it is zero (false), the loop ends and the program continues after it.
- If the condition is non-zero (true), the body runs.
- The iteration expression runs, then the program goes back to step 2.
Because the condition is tested before the body, a loop whose condition is false at the start never runs its body at all. For for (int i = 10; i < 5; ++i) the body executes zero times.
The init clause can be an expression or, since C99, a declaration. A variable declared there is in scope for the condition, the iteration expression and the body, and it goes out of scope when the loop ends. That is why two loops in a row can both declare int i without a clash. C89/C90 does not allow the declaration form, so code for that standard has to declare the variable above the loop. GCC's documentation lists the -std= options that select a language standard, and as of the page I checked, its default for C code is GNU C23, so the declaration form works without any flag.
Count up, count down and change the step
The update clause does not have to be ++i. Any expression works, so you can step by 2, or count down:
for (int i = 0; i < 10; i += 2) { printf("%d ", i); } /* 0 2 4 6 8 */
for (int i = 5; i > 0; --i) { printf("%d ", i); } /* 5 4 3 2 1 */
The comments show what each loop prints. In both cases the condition decides when to stop, so check the boundary: i < 10 excludes 10, while i <= 10 includes it.
Loop over an array
An array in C has no built-in length you can ask for at run time, so the loop needs the element count. For an array declared in the same scope, sizeof scores / sizeof scores[0] gives the number of elements. Here is a sum and an average:
#include <stdio.h>
#include <stddef.h>
int main(void)
{
int scores[] = {72, 85, 90, 64};
size_t count = sizeof scores / sizeof scores[0];
int sum = 0;
for (size_t i = 0; i < count; ++i) {
sum += scores[i];
}
printf("sum=%d average=%.2f\n", sum, (double)sum / count);
return 0;
}
Example output:
sum=311 average=77.75
The index type is size_t, the unsigned type that sizeof produces, which avoids a signed/unsigned comparison warning. That choice has a catch when you count down, covered below. Note that sizeof scores / sizeof scores[0] only works where the array itself is visible. Inside a function that received the array as a parameter, sizeof gives the size of a pointer, so pass the length as a separate argument.
Nested for loops
A loop inside a loop runs its full cycle once for every iteration of the outer loop. A 3 by 3 multiplication table:
for (int row = 1; row <= 3; ++row) {
for (int col = 1; col <= 3; ++col) {
printf("%d ", row * col);
}
printf("\n");
}
Example output:
1 2 3
2 4 6
3 6 9
The body of the inner loop runs 3 x 3 = 9 times. Nesting multiplies the work, so two loops over 10,000 items each mean 100 million iterations.
break and continue inside a for loop
continue skips the rest of the current iteration. In a for loop, control jumps to the iteration expression, so the counter still advances. This prints only the odd numbers:
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0) {
continue;
}
printf("%d ", i);
}
Example output:
1 3 5 7 9
That behaviour is a difference from a while loop, where a continue placed before a hand-written increment can skip the increment and loop forever.
break ends the loop at once. This finds the position of the first negative number:
int values[] = {4, 9, -2, 7};
int found = -1;
for (int i = 0; i < 4; ++i) {
if (values[i] < 0) {
found = i;
break;
}
}
printf("first negative at index %d\n", found);
Example output:
first negative at index 2
A break leaves only the innermost loop. The cppreference page for break says it cannot be used to break out of multiple nested loops and points to goto for that case. In practice, moving the nested loops into a function and using return is usually cleaner than a goto.
Two variables and the comma operator
The init and update clauses can each hold several expressions separated by commas. Two indexes that move towards each other reverse an array in place:
int nums[] = {1, 2, 3, 4, 5};
for (int lo = 0, hi = 4; lo < hi; ++lo, --hi) {
int swap = nums[lo];
nums[lo] = nums[hi];
nums[hi] = swap;
}
/* nums is now {5, 4, 3, 2, 1} */
In the init clause int lo = 0, hi = 4 is one declaration with two variables, so both have the same type. In the update clause, the comma is the comma operator, which evaluates its left side and then its right.
The infinite loop: for(;;)
Every clause is optional. If the condition is left out, C replaces it with a non-zero constant, so the loop never ends by itself:
for (;;) {
/* runs until break, return, goto or exit */
}
Use it for loops whose exit depends on something in the middle of the body, such as a menu loop that ends when the user types "quit". The body can also be empty: a lone ; is a valid null statement. That is exactly what causes the first bug below.
Common for loop mistakes in C
- Off by one. For an array of
nelements the valid indexes are 0 ton - 1. Writingi <= nreads one element past the end, which is undefined behaviour: it may print garbage, appear to work, or crash. Usei < n. - A stray semicolon.
for (int i = 0; i < 3; ++i);followed by a block makes the semicolon the loop body. The loop spins three times doing nothing, and the block after it runs once. Some compilers warn about this and some do not, so check the line yourself. - Counting down with an unsigned index.
for (size_t i = n - 1; i >= 0; --i)never ends, because an unsigned value is always at least 0 and0 - 1wraps to the largest value. Use this form instead, which tests the old value and then decrements:
for (size_t i = n; i-- > 0; ) {
printf("%zu ", i);
}
With n equal to 3, example output is 2 1 0.
- Changing the counter in the body. Modifying
iinside the body is legal, but it makes the loop hard to read and a common source of skipped or repeated elements. If you need irregular steps, say so in the update clause. - Floating-point counters. A step such as 0.1 cannot be stored exactly in binary floating point, so a condition like
x != 1.0may never be hit. Count with an integer and compute the float from it:double x = i * 0.1;.
When to use for, while or do-while
Use for when you know the count or can express the loop as start, stop and step. Use while when the loop runs until a condition changes, for example until fgets returns NULL. Use do-while when the body must run at least once before the first test. The three are interchangeable in what they can express, so the choice is about readability.
If you are comparing languages, the same idea in other syntaxes is covered in JavaScript for loop: syntax and examples and bash for loop examples. When a problem is naturally self-similar, such as a tree or a factorial, a function that calls itself can replace the loop; see recursion in C for how that works.
Frequently asked questions
- Can you declare the loop variable inside a for loop in C?
- Yes, since C99. Writing for (int i = 0; i < 5; ++i) declares i in the init clause, and i is only visible inside the loop. In C89/C90 you must declare the variable before the loop. Any modern compiler accepts the C99 form, though some older ones need a flag such as -std=c99.
- What does for(;;) do in C?
- It is an endless loop. All three clauses of a for statement are optional, and when the condition is omitted C treats it as a non-zero constant, so the condition is always true. The loop only ends through break, return, goto or by terminating the program.
- What is the difference between a for loop and a while loop in C?
- They can express the same loops. A for loop puts the initialisation, the condition and the update on one line, which suits loops with a counter. A while loop only has a condition, which suits loops that run until some state changes, such as reading input until it ends.
- How do I break out of nested for loops in C?
- break only leaves the innermost loop. To leave several loops at once, use goto to a label after the outer loop, return from the function, or set a flag that the outer loop's condition checks.