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

Initialization, condition, and increment flow

Initialization, condition, and increment flow

What you'll learn: How the three distinct parts of a for loop work together in a specific sequence to manage repetitive tasks.

The anatomy of a loop

A for loop is like a automated physical trainer. Before you start, the trainer sets a goal (like 10 reps), checks if you’ve reached that goal yet, and counts each finished rep. In C, these three steps are packed into one line to keep your code organized.

The syntax looks like this: for (initialization; condition; increment)

The step-by-step flow

Think of the loop as a circular path. It doesn't run all at once; it follows a strict order of operations:

  1. Initialization: This happens exactly once, at the very beginning. It’s where you create your counter (usually an integer like i) and set its starting value.
  2. Condition: Before every lap, the computer asks: "Is this true?" If yes, it runs the code inside the curly braces. If no, the loop ends immediately.
  3. The Body: The code inside the {} runs.
  4. Increment: This happens at the end of every lap. It updates your counter (usually adding 1), then the computer jumps back to Step 2 to check the condition again.

Seeing it in action

Let’s look at a loop that counts to three:

#include <stdio.h>

int main() {
    // 1. Init (i=1) -> 2. Check (1<=3?) -> 3. Print -> 4. Inc (i becomes 2)
    for (int i = 1; i <= 3; i++) {
        printf("Lap number %d\n", i);
    }
    
    return 0;
}

In this example, int i = 1 sets the stage. The loop checks if i is less than or equal to 3. Since it is, it prints the message. Only after printing does i++ turn the 1 into a 2. The cycle repeats until i becomes 4. At that point, the condition 4 <= 3 is false, and the loop shuts down.

Why this order matters

The most important thing to remember is that the increment happens last. The code inside your loop will always run using the "current" value before the counter gets updated for the next round. This ensures you don't accidentally skip your first number or count one time too many.

Key takeaway

The for loop initializes once, checks the condition before every lap, and increments the counter after every lap.