C & C++ fundamentals / 08

for loops

Understand a for loop's initialization, condition, and update, then compare it with a while loop.

On this page

Today we will look at the for loop, another way to repeat statements. Its structure is for (initialization; condition; update) {}. A common example initializes a variable named i, checks it against a limit, and updates it with i++.

The three parts

  1. Initialization runs once at the start and sets the initial value.
  2. Condition is checked before the body runs. If it is true, the body executes; if false, the loop ends.
  3. Update runs after the body, usually changing the loop variable before the next condition check.

There are many variations, but this is the basic pattern. Let's write a short program:

#include <stdio.h>

int main()
{
    for(int i=0;i<5;i++)
    {
        printf("Hello World!\n");
    }
    return 0;
}

We declare i inside the loop because it is only needed there. If you need to use the variable afterward, you would normally declare it outside the loop.

The condition i < 5 permits the body to run while i is less than five. The update i++ increases it by one after each iteration. The program prints Hello World! five times.

The equivalent while example

We can rewrite the example with a while loop and obtain the same printed result:

#include <stdio.h>

int main()
{   
    int i=0;

    while(i<5)
    {
        i++;
        printf("Hello World!\n");
    }
    return 0;
}

Translation note: initialization happens once, not on every iteration. The original prose blurred initialization with the repeated condition check; the sequence above makes that distinction explicit.

Next, we will apply loops to more involved examples.

Moved here from Tistory

I migrated this post from my Korean Tistory blog, I am Jason Lee, to this website and translated it into English. My writing and projects now live together in one place.

The original publication date, code examples, and screenshots are preserved. Editorial notes clarify known issues in the original material.

Original post on Tistory English edition · Aug 30, 2026
← Back to all articles