OverIQ.com

The for loop in C

Last updated on July 27, 2020


In the last two chapters, we have learned about the while and do while loop. In this chapter we discuss the for loop: The syntax of the for loop is as follows: Syntax:

1
2
3
4
5
6
for(expression1; expression2; expression3)
{
    // body of for loop
    statement1;
    statement2;
}

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

How it works:

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

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

1
2
3
4
5
6
7
8
9
for(expression1; expression2; expression3)
    statement1;

// The above for loop is equivalent to:

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

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include<stdio.h>

int main()
{  
    int i;   // loop variable
    int sum = 0;    // variable to accumulate sum

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

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

    // return 0 to operating system
    return 0;
}

Expected Output:

Sum = 5050

How it works:

In line 5, we declare a loop variable named i. In line 6, we declare and initialize a variable named sum to 0. Then the program control enters the for loop. At first, the initialization statement (i=1) is executed to initialize loop variable i. Then the condition (i<100) is checked, if it is true, statements inside the body of the for loop are executed. After executing the body of the loop the program control transfers to the update expression (i++), and the value of i is incremented by 1. Then the condition (i<100) is checked again, if it is still true, the body of the loop is executed. This process continues as long as the variable i is less than or equal to 100. When i reaches 101, the condition (i<100) becomes false and control comes out of the for loop to execute statements following it.

Is there any difference between the while and the 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 a while loop and vice versa.

1
2
3
4
5
expression1;
while(expression2)
{
    expression3;
}

In the above snippet, the expression1 can be treated as initialization expression because it is executed only once at the beginning of the while loop. The expression2 is the test expression and expression3 is the update expression. Applying this pattern to our previous for loop example, let’s rewrite it using the while loop.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include<stdio.h>

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

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

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

    // return 0 to operating system
    return 0;
}

Expressions in the for loop are Optional #

All the three expressions inside the for loop are optional, but the two semicolons must always be present.

  • We can omit the expression1 if the initialization is done outside the for loop.
  • If the expression2 is omitted then the condition is always true, leading to the creation of an infinite loop - a loop which never stops executing. To avoid infinite loops you should include a break or return statement within in the loop body. We discuss the break and return statements in detail in upcoming chapters.
  • We can omit the expression3 if the update expression is present inside the body of the for loop.

The following are some simple variations of the for loop based on the expressions omitted:

Example 1: The expression1 is omitted.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
     1st variation - expression1 is omitted
*/

#include<stdio.h>

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

    //expression 1 is omitted

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

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

    // return 0 to operating system
    return 0;
}

Expected Output:

Sum = 5050

In this case, the expression1 is omitted because the initialization of the loop variable is performed outside of the for loop (line 9). Note that although the expression1 is omitted both the semicolons ( ; ) must be present.

Example 2: The expression2 is omitted.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
  2nd variaton - expression2 is omitted
*/

#include<stdio.h>

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

   for(i = 1 ; ; i++)  // expression 2 is omitted
   {
       if(i > 100)
       {
            /* the break statement causes the loop to terminate.
               We will discuss the break statement in detail
               in later chapters.
             */
            break;
        }
        sum += i;
    }
    printf("Sum = %d", sum);

    // return 0 to operating system
    return 0;
}

Expected Output:

Sum = 5050

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>100) is checked, if it is false then the statement inside the if block is omitted. When i reaches 100, the condition (i>100) becomes true and the break statement is executed, causing the loop to terminate and the program execution resumes with the statement following the loop.

Note: The break statement causes an exit from the loop. It is discussed in detail in the chapter The break and continue statement in C.

Example 3: The expression3 is omitted.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 3rd variation - expression3 is omitted
*/

#include<stdio.h>

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

    // expression3 is omitted

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

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

    // return 0 to operating system
    return 0;
}

Expected Output:

Sum = 5050

Here the third expression is omitted. To compensate for the third expression, we have added i++; just after the sum += i; statement.

Example 4:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*
   4th variation - all the expressions are omitted
*/
#include<stdio.h>

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

    for( ; ; )
    {
        if(i > 100) // condition
        {
            break; // break out of the for loop
        }
        sum += i;
        i++; // update expression
    }

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

    // return 0 to operating system
    return 0;
}

Expected Output:

Sum = 5050

Nesting of Loops #

Just as if-else statement can be nested inside another if-else statement, we 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 nested for loop to print half pyramid pattern:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include<stdio.h>

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

    for(row = 0; row < 10; row++)  // number of lines
    {
        for(col = 0; col < row; col++)  // num of * in each lines
        {
            printf(" * ");
        }
        printf("\n");
    }

    // return 0 to operating system
    return 0;
}

Expected Output:

1
2
3
4
5
6
7
8
9
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *

How it works:

In line 5, we have declared and initialized two integer variables row and col.

In lines 7-14, we have a nested for loop. The outer for loop controls the number of lines to print and the inner for loop controls the number of * to print in each line.

When outer for loop is executed value of the row variable is initialized to 0, then the condition (row<10) is tested, since it is true (0<10) the control comes inside the body of the outer for loop, which is another for 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, the 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 the inner for loop. The printf() statement in line 13 prints a newline (\n) character . 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 row is 1). The condition (row<10) is tested, since it is true (1<10). The body of the outer for loop is executed once more. This process will keep repeating until row<10. When row reaches 10, the condition row < 10 becomes false and control comes out the outer for loop.