C ยท Chapter 15 of 45

C For Loop

The for loop is ideal when you know in advance how many times you want to repeat something. It combines initialization, condition and increment into one compact line.

for loops are commonly used to iterate over arrays, count up or down, or repeat an action a fixed number of times.

Syntax
for (init; condition; increment) {
  // code
}

Anatomy of a for loop

A for loop has three parts separated by semicolons: initialization (runs once), condition (checked each iteration), and increment (runs after each iteration).

Nested for loops

A for loop can contain another for loop inside it, which is common when working with grids or multidimensional data like tables and matrices.

Example 1 (c)
#include <stdio.h>

int main() {
  for (int i = 0; i < 3; i++) {
    printf("%d\n", i);
  }
  return 0;
}
Output
0
1
2

The loop runs three times, printing i and incrementing it each pass.

Example 2 (c)
#include <stdio.h>

int main() {
  for (int i = 1; i <= 2; i++) {
    for (int j = 1; j <= 2; j++) {
      printf("%d,%d ", i, j);
    }
  }
  printf("\n");
  return 0;
}
Output
1,1 1,2 2,1 2,2 

The inner loop runs completely for each iteration of the outer loop.

Key points

  • for combines init, condition and increment in one line.
  • The loop variable is often scoped to the loop when declared inside it.
  • for loops can be nested for multidimensional tasks.
  • Any of the three for clauses can be left empty if not needed.
๐Ÿ’ก Note: A for loop and a while loop can often achieve the same result โ€” choose whichever is clearer for the task.

๐Ÿ“ Quick Quiz

1. What are the three parts of a for loop header?

2. How many times does `for (int i = 0; i < 5; i++)` run?

3. What is a nested for loop?