C For Loop

When you know exactly how many times you want to repeat something, the for loop is the cleanest choice. It packs the counter setup, the condition, and the update into a single line.

The for Loop

A for loop has three parts separated by semicolons: the initialization (runs once at the start), the condition (checked before each pass), and the update (runs after each pass). Keeping all three together makes counting loops easy to read.

A simple for loop

#include <stdio.h>

int main() {
  for (int i = 0; i < 5; i++) {
    printf("i is %d\n", i);
  }
  return 0;
}

This prints 0 through 4. First i is set to 0. Before each pass the condition i < 5 is checked. After each pass i++ increases i by 1. The loop stops once i reaches 5.

  • Statement 1 sets the starting value and runs only once.
  • Statement 2 is the condition that must be true to keep looping.
  • Statement 3 updates the counter after every pass.
Note: You can count by any step you like. Use i += 2 to skip by twos, or start the counter high and use i-- to count downward.

Counting even numbers up to 10

#include <stdio.h>

int main() {
  for (int i = 0; i <= 10; i += 2) {
    printf("%d is even\n", i);
  }
  return 0;
}

By using i += 2, the counter jumps 0, 2, 4, 6, 8, 10. This prints every even number from 0 to 10, showing how flexible the update step can be.

StatementWhen it runsPurpose
int i = 0Once, at the startSet the counter
i < 5Before each passDecide whether to continue
i++After each passMove the counter forward

Exercise: C For Loop

What are the three parts inside a for loop's parentheses, separated by semicolons?