The for loop in C

    The for loop executes a given code block multiple times. It simplifies the loop process when we need to repeat the body a fixed number of times. It handles the iterations, using three statements: initialization ; condition ; update.

Do you learn better from video?

Learn faster with deeper understanding!
The "Computer programming for beginners" course is the perfect place to begin with programming.

Start now!

Flowchart

for loop flowchart

    As you see, “for” is a pre-condition loop. The first thing that is executed in a for loop is the initialization statement. Then the condition is checked and if it is true the body is executed. After the body follows the update statement and then the condition.

    The iterations continue until the condition is evaluated to false. We can represent the logic like this:

Initialization – (Condition – Body – Update)

The statements in the parenthesis will execute for each repetition of the loop.

C for loop syntax

    for(initialization ; condition ; update)
    {
        Body of the loop
    }

     Note that all of these statements (excluding the body) are optional. If you choose to omit some of them, you still need to add the semicolon. In fact, one common way to write an infinite loop in C is:
    for(;;)
    {
    }

Initialization

    This is the first part that is executed. It is executed only once. Usually here, we will initialize an int variable.

    for (i = 0 ; …)

We can initialize more than one variable, separating them with commas.

    for (i = 0, j = 1 ; …)

    Note that the variables i and j were created before the loop. Before the C99 standard, it was not allowed to create a variable at this place. If your compiler complies with C99 or later, you can create and initialize the variable in the loop like this:

    for(int i = 1; ...)

    When you create a variable in this manner, its scope is limited to the for loop – its initialization, condition, update and body. Once the program leaves the loop that variable is out of scope and you cannot access it anymore.

Condition

    The condition statement executes with each iteration, just before the body block. In theory, you can place here any statement that returns any result. In practice here we compare our counting variable to the target number of executions.

    for(...; i < 10; ...)

If you omit the condition, it is always evaluated to true.

Update

    The update statement executes with each iteration, right after the body block. In theory here you can put any valid C statement. Normally, we just increment or decrement our counter variable(s).

    for(...; ...; i++)

We can also increment by a different step, by a factor or even use an entire expression.

Examples

The classic use:

    #include <stdio.h>

    int main()
    {
        int i;
        for(i = 1; i <= 10; i++)
        {
            printf("%d ", i);
        }
    }

    This simple example will print the numbers for 1 to 10. The actual output of the program is:
“1 2 3 4 5 6 7 8 9 10”

Different increment step:

    Write a function that sums all even numbers between 9 and 31. In this case we don’t need to iterate over the odd numbers. That’s why we use an increment step of 2, starting from the first even number in the interval:

    int sumEvens()
    {
        int i = 10;
        int sum = 0;
        for(; i < 31; i = i + 2)
        {
           sum += i;
        }
        return sum;
    }

Different increment step:

    Create a program in C that reads a sequence of numbers and finds the biggest of them. The first input tells how many numbers we need to read and compare. Use a for loop.

    void findMax()
    {     
        int count, i, currentNumber, max;
        printf("How many numbers do you want to compare? ");
        scanf("%d", &count);
        scanf("%d", &max);
        for(i = count; i > 1; i--)
        {
            scanf("%d", &tNumber);
            if(currentNumber > max)
                max = currentNumber;
        }
        printf("The biggest number is %d\n", max);
    }

    Here are all the examples in a zip file. It contains one source file with all the above examples.

See also:      

    This article is part of two tutorials: Basic C tutorial and keywords in C. Continue accordingly:

Previous lesson: do..while

Next lesson: arrays

Previous keywordfloat

Next keywordgoto

Do you learn better from video?

Learn faster with deeper understanding!
The "Computer programming for beginners" course is the perfect place to begin with programming.

Start now!


› for

› for

Did this help? Support me with your vote ;-)

Did this help?