Skip to content
Laviyx Learn

Try

C course menu

for Loop in C: Syntax, Examples, Counting Down and Looping Over Arrays

Master the C for loop: initialisation, condition and update, counting up, down and in steps, looping over arrays with sizeof, several loop variables, off-by-one errors, and common for loop patterns such as sums, maximums and searches.

Beginner5 min readUpdated
On this page

The for loop is the most common loop in C. It keeps the start, the condition and the step together on one line.

Syntax#

C
for (int i = 1; i <= 5; i++) {
    printf("%d ", i);
}
printf("\n");
Output
1 2 3 4 5 
  1. Initialisation (int i = 1): runs once, before the loop.
  2. Condition (i <= 5): checked before each repetition; the loop stops when it is false.
  3. Update (i++): runs after each repetition.

A variable declared in the header (int i) exists only inside the loop (C99 and later).

Different steps#

C
for (int i = 10; i >= 0; i -= 2) printf("%d ", i);
printf("\n");
for (int i = 1; i <= 1000; i *= 10) printf("%d ", i);
printf("\n");
Output
10 8 6 4 2 0 
1 10 100 1000 

Looping over an array#

Array indexes run from 0 to length - 1. The number of elements can be calculated with sizeof:

C
#include <stdio.h>

int main(void) {
    int marks[] = {72, 95, 58, 88, 64};
    size_t count = sizeof marks / sizeof marks[0];

    int total = 0, best = marks[0];
    for (size_t i = 0; i < count; i++) {
        total += marks[i];
        if (marks[i] > best) best = marks[i];
    }
    printf("Count: %zu, total: %d, best: %d\n", count, total, best);
    printf("Average: %.1f\n", (double)total / count);
    return 0;
}
Output
Count: 5, total: 377, best: 95
Average: 75.4

sizeof marks / sizeof marks[0] (total bytes divided by bytes per element) only works where the array itself is visible. Once an array is passed to a function it becomes a pointer, and you must pass its length separately (Pointers and Arrays).

Off-by-one errors#

The most common loop bug is running one time too many or too few:

C
int a[5];
for (int i = 0; i <= 5; i++) a[i] = 0;   /* bug: a[5] does not exist */

a[5] is past the end of the array. C does not check this: it writes into memory that belongs to something else, which is undefined behaviour. For an array of n elements, the condition is i < n.

Several variables#

The comma lets a for loop manage two variables, for example to walk from both ends towards the middle:

C
int a[] = {1, 2, 3, 4, 5, 6};
int n = 6;
for (int i = 0, j = n - 1; i < j; i++, j--) {
    int tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
}
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
Output
6 5 4 3 2 1 

Optional parts#

All three parts are optional. for (;;) is an infinite loop, a common idiom alongside while (1).

Practice#

Practice exercise

Using a for loop, print all the prime numbers below 30 on one line. (A prime has no divisors other than 1 and itself; test divisors up to the square root.)

Show solution
C
#include <stdio.h>

int main(void) {
    for (int n = 2; n < 30; n++) {
        int is_prime = 1;
        for (int d = 2; d * d <= n; d++) {
            if (n % d == 0) {
                is_prime = 0;
                break;
            }
        }
        if (is_prime) printf("%d ", n);
    }
    printf("\n");
    return 0;
}
Output
2 3 5 7 11 13 17 19 23 29 

Key takeaway#

Finished this lesson?