August 31, 2018

The for Loop in C


   The for loop provides a mechanism to repeat one or more statements until a particular condition is met. Condition may be predefined or open-ended.


The syntax and general form of a for loop is:

for(initialization_expr; test_expr; update_expr)
{
    /* body of the loop */
   
    Statement Block;
}




Here is the flow of control in a for loop:

  1. The initialization expression is evaluated. It is typically used to initialize a counter or other variable that must have a starting value. This is the first action performed by the loop and it is only done once.

  2. The test expression is evaluated. The test expression is a relational expression that determines the number of the iterations desired or the condition to exit the loop. If this evaluates to false, then the loop terminates immediately. If this evaluates to true then the statement block is executed.

  3. After the statement block is executed, the update expression is evaluated. It executes at the end of each iteration. Typically, this expression is used to increment or decrement the variables declared in the initialization expression. After the update expression has been evaluated, the loop returns to step 2.


Flow of control in a for loop



 Flow Diagram:

Flow Diagram of For Loop


Note:

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

for(initialization_expr; test_expr; update_expr)
    statement;


Example:

The following program uses for loop to print numbers from 1 to 10.

#include <stdio.h>

int main(void)
{
    int i;
  
    for(i=1; i<11; ++i)
    {
        printf("%d \n", i);
    }
  
    return 0;
}


 Output :

1
2
3
4
5
6
7
8
9
10


Explanation:

  • First, we declare a loop variable named i, and assign it the value 1.
  • Second, the condition i<11 is tested. Since i is 1, the condition 1<11 evaluates to true. Consequently, the statement executes, which prints 1.
  • Third, ++i is evaluated, which increments i to 2. Then the loop goes back to the second step.
  • Now, 2<10 is evaluated to true, so the loop iterates again. The statement prints 2, and i is incremented to 3. 3<10 evaluates to true, the statement prints 3, and i is incremented to 4. And so on.
  • Eventually, i is incremented to 11, 11<11 evaluates to false, and the loop exits.



In most cases, the for loop can be represented with an equivalent while loop as follows:

initialization_expr;
while(test_expr)
{
    /* body of the loop */
    Statement Block;
       
    update_expr;
}


Let's rewrite the above for loop example by converting it into an equivalent while loop:


#include <stdio.h>

int main(void)
{
    int i=1;
 
    while(i<11)
    {
        printf("%d \n", i);
       
        ++i;
    }
 
    return 0;
}



Note: Since the for loop performs a pre-test, it's possible that it will never iterate. Here is an example:

for(i=100; i<99; ++i)
    printf("Hello World \n");


Since the variable i is initialized to a value that makes the test expression false from the beginning, this loop terminates as soon as it begins.


WARNING! Be careful not to place a statement in the body of the for loop that duplicate the update expression. For example, the following loop increments i twice for each iteration:

for(i=0; i<10; ++i)
{
    printf("Hello World \n");
    ++i;
}





Omitting the for Loop's Expressions

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.


Omitting initialization expression

The initialization expression may be omitted from inside the for loop's parentheses if it has already been performed, or no initialization is needed.

Example:

#include <stdio.h>

int main(void)
{
    int i=1;
 
    /* initialization expression is omitted */
 
    for( ; i<11; ++i)
    {
        printf("%d \n", i);
    }
 
    return 0;
}


 Output :

1
2
3
4
5
6
7
8
9
10

Explanation :

In this program initialization is done before for statement. In for statement only condition and increment is done.



Omitting test expression  

If test expression 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.



Example:

#include <stdio.h>

int main(void)
{
    int i;
 
    /* test expression is omitted */
 
    for(i=1; ; ++i)
    {
        if(i>10)
        {
            break;
        }
        printf("%d \n", i);
    }
 
    return 0;
}


 Output :

1
2
3
4
5
6
7
8
9
10

Explanation :

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>10) is checked, if it is false then the statement inside the if block is omitted. When i reaches 11, the condition (i>10) 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 upcoming tutorial.



Omitting update expression


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


Example:

#include <stdio.h>

int main(void)
{
    int i;
 
    /* update expression is omitted */
 
    for(i=1; i<11; )
    {
        printf("%d \n", i);
        ++i; /* update expression */
    }
 
    return 0;
}


 Output :

1
2
3
4
5
6
7
8
9
10

Explanation :

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


Omitting all expressions


Example:


#include <stdio.h>

int main(void)
{
    int i=1;
 
    /* all three expression is omitted */
 
    for( ; ; )
    {
        if(i>10)
        {
            break;
        }
        printf("%d \n", i);


        ++i; /* update expression */
    }
   
 
    return 0;
}

Output :
1
2
3
4
5
6
7
8
9
10


 Multiple declarations

The initialization expression and update expression in a for loop can have any number of expressions separated by comma operator. The use of comma operator ensures that the expressions are evaluated from left to right. In this way we can have more than one loop control variable which can be initialized and updated in a single for loop.


#include <stdio.h>

int main(void)
{
    int i,j;

    for(i=0, j=9; i<10; ++i, --j)
    {
        printf("%d   %d \n", i,j);
      
    }
 
    return 0;
}
 

Output :

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


next    The do-while Loop in C
top    Index
prev    The while Loop in C



No comments:

Post a Comment