Lesson 58 +10 XP

For Loops

For Loops

When you know exactly how many times to repeat, the for loop is the tidy way.

The basic form

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

The three parts

A for loop has three sections in its header:

  • Start: int i = 0 - sets the starting value.
  • Condition: i < 5 - checked before each round.
  • Update: i++ - changes the counter each round.

How it flows

  1. Run the start once.
  2. Check the condition; if false, stop.
  3. Run the body.
  4. Run the update.
  5. Back to step 2.

Output

0
1
2
3
4

Counting down

for (int i = 5; i > 0; i--) {
    printf("%d\n", i);
}

TL;DR

  • for (start; condition; update) { ... }.
  • Start runs once; condition gates each round; update changes each round.
  • Perfect when you know the exact count.
  • Works in either direction with i++ or i--.