The for loop in C

The for loop is another type of loop C provides.

Syntax:

for(expression1; expression2; expression3)
{
    statement1;
    statement2;
}

expression1 is the initialization expression.
expression2 is the test expression or condition.
expression3 is the update expression.

How it works

First initialization expression is executed (i.e expression1 ) to initialize loop variables. expression1 executes only once when the loop starts. Then the condition is checked (i.e expression2 ), if the condition is true, then the body of the loop is executed. After executing the body the control transfers back to the expression3. expression3 modifies loop variables then again condition is checked (i.e expression2). If the condition is still true then the body of the loop executed. This process continues until expression2 becomes false.

for-loop-structure-in-c

If the body of for loop contains only one statement then braces ({}) can be omitted.

for(expression1; expression2; expression3)
    statement1;

The following program calculates the sum of numbers from 1 to 1000.

#include<stdio.h>

int main()
{  
    int i, sum = 0;

    for(i = 1; i <= 1000; i++)
    {
        sum += i;
    }

    printf("Sum = %d", sum);

    // signal to operating system program ran fine
    return 0;
}
``

**Expected Output:**

```none
Sum = 500500

How it works:

In line 6, two integer variables i and sum are declared. And the variable sum is initialized to 0. Then the control enters the for loop. Firstly initialization statement (i=1) is executed to initialize loop variable i. Then the condition (i<1000) is checked, if it is true, statements inside the body of the for loop are executed. After executing the body of the loop control transfers to update expression (i++), and the value of i is incremented by 1 , then again condition (i<1000) is checked, if it is still true, the body of the loop executed. This process continues as long as variable i is less than or equal to 1000. When i reaches 1001, the condition (i<1000) becomes false and control comes out of the for loop.

Is there any difference between while and for loop ?

The while and for loop essentially do the same thing in different ways. In fact, except in a few rare cases, a for loop can always be replaced by while loop and vice versa.

expression1;
while(expression2)
{
    expression3;
}

As you can see expression1 is initialization expression executed only once at the beginning of the loop. Then expression2 is the test expression or condition. And expression3 is the update expression. Applying this pattern to our previous for loop example, let’s rewrite it using while loop.

#include<stdio.h>

int main()
{
    int i = 1, sum;

    while(i < 1000)
    {
        sum += i;
        i++;
    }

    printf("Sum = %d", sum);

    // signal to operating system program ran fine
    return 0;
}

Omitting expressions in for loop #

All the three expression inside the for loop is optional. You are free to omit one or all three expressions, but in any case, two semicolons must be present.

expression1 can be omitted when initialization is done outside the for loop.

If expression2 is omitted then the condition is always assumed to be true and so this type of loop never stops executing. This type of loop is known as an infinite loop. To avoid this you should include a statement that takes you out of the for loop.

expression3 is omitted when update statement is present inside the body of the for loop.

The following are some simple variations of for loop as mentioned above.

Example 1:

/*
     1st variation: Where expression1 is omitted
*/

#include<stdio.h>

int main()
{
    int i = 1, sum = 0;

    //expression 1 is omitted

    for( ; i < 1000; i++)
    {
        sum += i;
    }

    printf("Sum = %d", sum);

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

Sum = 499500

Nothing new except variable i has been initialized by a separate assignment statement outside the for loop, that’s why we have omitted the first expression in the for loop. Although expression1 is omitted both semicolons(;) must be present.

Example 2:

/*
  2nd variaton: Where expression2 is omitted
*/

#include<stdio.h>

int main()
{
    int i, sum = 0;
    // expression 2 is omitted

    for(i = 1 ; ; i++)
   {
       if(i > 1000)
       {
            /* the break statement takes the control out of
               for loop when i becomes greater
               than 100. We will discuss in detail
               how break statement works in later chapter.
             */
            break;
        }
        sum += i;
    }
    printf("Sum = %d", sum);

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

Sum = 499500

Here the condition is omitted. To compensate for the condition, we have added an if statement. When control comes inside the body of for loop, the condition (i>1000) is checked, if it is false then the statement inside the if block is omitted . When i reaches 1000 , the condition (i>1000) becomes true. And the break statement is executed, and the control comes out of the for loop.

Note: break statement is used to break out of the loop. The break statement will be discussed in detail in later chapters.

Example 3:

/*
 3rd variation: Where expression3 is omitted
*/

#include<stdio.h>

int main()
{
    int i, sum = 0;

    // expression3 is omitted

    for(i = 1 ; i < 1000 ; )
    {
        sum += i;
        i++; // update expression
    }

    printf("Sum = %d", sum);

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

Sum = 499500

Here the third expression is omitted. To compensate for the third expression, we have added i++ just after printf() statement.

Example 4:

/*
   4th variation: All expression are omitted
*/
#include<stdio.h>

int main()
{
    int i = 0, sum = 0; // initialization expression

    for( ; ; )
    {
        if(i > 999) // condition
        {
            break;
        }
        sum += i;
        i++; // update expression
    }

    printf("Sum = %d", sum);

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

Sum = 499500

Nesting of loops #

Just as if... else statement can be nested inside another if or else statement, you can nest any type of loop inside any other type. For example a for loop can be nested inside another for loop or inside while or do while loop. Similarly, while and do while can also be nested.

The following program uses a for loop inside another for loop to create a simple pattern.

#include<stdio.h>

int main()
{
    int row = 0, col = 0;

    for(row = 0; row < 10; row++)
    {
        for(col = 0; col < row; col++)
        {
            printf(" * ");
        }
        printf("\n");
    }

    // signal to operating system everything works fine
    return 0;
}

Expected Output:

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *

How it works

In line 5, we have declared two integer variables row and col. When outer for loop is executed value of the row variable is initialized to 0, then the condition (row<5) is tested, Since it is true (0<5) . The statement in the body of the loop is executed. Then the control comes inside the body of the for loop, which is another for the loop. In the inner for loop variable col is initialized to 0, then the condition (col<=row) is checked, since it is true (0<=0) . The statement inside the body of the inner loop is executed i.e printf(" * ") . Then col is incremented by 1 using update expression col++ (now the value of col is 1 ). The condition (col<=row) is tested again, since it is false (1<=0) . Control breaks out of inner for loop. The printf() statement in line 16 prints a newline. Since there are no more statements left to execute, control transfers to the update expression of the outer for loop. The value of the row is incremented by 1 (now i is 1). The condition (row<5) is tested, since it is true (1<5). The body of the outer for loop is executed once more. This process will keep repeating until row<5. When row reaches 5, the condition row < 5 becomes false and control comes out the outer for loop.