Course contentsShow
← C
Lesson 282 of 1,2194. Control FlowFree lesson

The three parts of a for loop header

The three parts of a for loop header

What you'll learn: You will learn how to read and write the three specific expressions that control how a for loop behaves.

The Recipe for Repetition

Think of a for loop like a treadmill workout. Before you start running, you set your starting speed, you decide how long you’ll keep going, and you decide how much to increase the intensity each minute.

In C, a for loop header lives inside parentheses and uses semicolons to separate three distinct instructions. It looks like this:

for (initialization; condition; update) {
    // The code that runs repeatedly
}

1. The Initialization (The Starting Point)

The first part runs exactly once, right before the loop begins. This is where you usually create a "counter" variable and give it a starting value. It’s like placing your finger at the start of a list.

  • Example: int i = 0;

2. The Condition (The Gatekeeper)

The middle part is a true/false question asked before every lap. If the answer is "true," the code inside the curly braces runs. If it’s "false," the loop stops immediately. This prevents the loop from running forever.

  • Example: i < 5; (Keep going as long as i is less than 5).

3. The Update (The Step Forward)

The final part runs after every lap is finished. Its job is to change the counter so you eventually reach the end. Without this, your counter would never change, and the gatekeeper would let you run forever.

  • Example: i++ (Add 1 to i after each lap).

Putting it Together

Here is how those three parts look in a real piece of code that prints "Hello" three times:

#include <stdio.h>

int main() {
    // 1. Start at 0; 2. Stop if i reaches 3; 3. Add 1 each time
    for (int i = 0; i < 3; i++) {
        printf("Hello!\n");
    }
    return 0;
}

In this example, the loop starts at 0, checks if 0 is less than 3 (it is!), prints the message, and then adds 1 to i. It repeats this cycle until i becomes 3, at which point the condition becomes false and the loop ends.

Key takeaway

A for loop header uses three parts—initialization, condition, and update—to precisely control when a loop starts, how long it lasts, and how it progresses.