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

Using the for loop as a counter

Using the for loop as a counter

What you'll learn: How to use the for loop to repeat a block of code a specific number of times by managing a built-in counter.

The mechanical counter

Imagine you are at the gym doing push-ups. You have a mental plan: start at zero, check if you’ve reached ten yet, and add one to your count every time you push up.

In C, the for loop is the perfect tool for this kind of repetition. It packs the setup, the goal, and the counting step into one single line. Instead of manually writing the same line of code ten times, you tell the computer how to count for you.

The three parts of the loop

A for loop uses three instructions separated by semicolons inside parentheses:

  1. Initialization: Where do we start? (e.g., int i = 0;)
  2. Condition: When do we stop? The loop keeps running as long as this is true. (e.g., i < 5;)
  3. Increment: How do we update the count after each round? (e.g., i++ to add one).

The code in action

Here is how you would tell a program to say "Hello" exactly five times:

#include <stdio.h>

int main() {
    // Start at 0; keep going while i is less than 5; add 1 each time
    for (int i = 0; i < 5; i++) {
        printf("Push-up number %d\n", i + 1);
    }

    return 0;
}

How it flows

When the computer hits the for loop, it creates the variable i and sets it to 0. It checks if 0 < 5. Since that is true, it runs the code inside the curly braces.

Once the code inside is finished, the computer jumps back to the top, performs the i++ (making i equal to 1), and checks the condition again. This repeats until i reaches 5. At that point, the condition 5 < 5 becomes false, and the computer skips past the loop to the rest of the program.

Using i as the variable name is a long-standing tradition in programming (short for "index" or "iterator"), but you can think of it simply as your "lap counter."

Key takeaway

The for loop automates counting by grouping the start value, the stop condition, and the step increment into one clean line.