Loops in C: For, Do-While, Nested Loops Statements

Loops in C: For, Do-While, Nested Loops Statements

Loops:

Loops are used when we want to execute a part of the program or a block of statements several times. For example, suppose we want to print "C is the best" 10 times. One way to get the desired output is - we write 10 printf statement and only one printf statement, and this approach is definitely better than the first one. With the help of loop we can execute a part of the program repeatedly till some condition is true. There are three loop statements in C-

  1. while
  2. do while
  3. for

While Loop:

The while statement can be writen as:
while (condition)
statement;

                                                    while (condition)
                                                    {
                                                         statement;
                                                         statement;
                                                         ------
                                                    }
    

Flow chart of while loop


Like if-else statement here also we can have either a single statement or a block of statements, a here it is known as the body of loop. Now let's see how this loop works. First the condition is evaluated; if it is true then the statements in the body of loop are executed. After the execution, again the condition is checked and if it is found to be true then again the statement in the body of loop are executed. This means that these statement are executed continuously till to condition is true and when it becomes false, the loop terminates and the control comes out of the loop. Each execution of the loop body is known as iteration.


Example 1.1:

/* Program to print the numbers from 1 to 10 using while loop*/
#include <stdio.h>
int main()
{
    int i = 1;
    while( i <= 10 )
    {
        printf("%d\t",i);
        i++; /*Statement that changes the value of conditon */
    }
    printf("\n");
    return 0;
}

Output:

 1       2       3       4       5       6       7       8       9       10

Here initially the condition (10 => i) is true. After each iteration of the loop, value of i increases: when the value of i equals 11 the condition becomes false and the loop terminates.
Note that inside the body of the loop there should be a statement that alters the value of the condition, so that the condition becomes false ultimately at some point.


Example 1.2:

/* Program to print the numbers in reverse order with a difference of 2*/ 
#include<stdio.h>
int main()
{
    int i = 10;
    while( i >= 2)
    {
        printf("%d\t",i);
        i=i-2; 
    }
    printf("\n");
    return 0;
}

Output:

 10    8    6    4    2

do...while loop:

The 'do...while' statement is also used for looping. The body of this loop may contain a single statement or a block of statements. The syntax for writing this loop is:

         do
            statement;
            while(condition);
      

                                             do
                                              {
                                                    statement;
                                                    statement;
                                                    ------
                                              }while(condition);

Flow chart of do...while loop


Here firstly the statement inside loop body are executed and then the condition is evaluated. If the condition is true, then again the loop body is executed and this process continues until the condition becomes false. Note that unlike while loop, here a semicolon is placed after the condition.

In a 'while' loop, first the condition is evaluated and then the statements are executed whereas in a do while loop, first the statements are executed and then the condition is evaluated. So if initially the condition is false the while loop will not execute at all, whereas the do while loop will always executed at least once.


Example 1.1:


/* Program to print the numbers from 1 to 10 using do...while loop*/
#include<stdio.h>
int main()
{
    int i = 1;
    do
    {
        printf("%d\t", i);
        i++;
    } while (i <= 10);
    printf("\n");
    return 0;
}


Output:

 1       2       3       4       5       6       7       8       9       10

for loop:

The 'for' statement is very useful while programming in C. It has three expression and semicoluns are used for separating these expressions. The 'for' statement can be written as-

      for(expression1; expression2; expression3)
           statement;
      for(expression1; expression2; expression3)
      {
           statement;
           statement;
           ------
       }    
      

The loop body can be a single statement or block of statements.
expression1 is an initialization expression, expression2 is a test expression or condition and expression3 is an update expression. expression1 is executed only once when the loop starts and is used to initialize the loop variables. This expression is generally an assignment expression. expression2 is a condition and is tested before each iteration of the loop. This condition generally uses relational and logical operators. expression3 is an update expression and is executed each time after the body of the loop is executed.

Now let us see how this loop works. Firstly the initialization expression is executed and the loop variables are initialized, and then the condition is checked, if the condition is true then the body of loop is executed. After executing the loop body, control transfers to expression3(update expression) and it modifies the loop variables and then again the condition is checked, and if it is true, the body of loop is executed. This process continues till the condition is true and when the condition becomes false the loop is terminated and control is transferred to the statement following the loop.
The work done by the for loop can be performed by writing a while loop as-


Flow chart of for loop

          expression 1;
          while (expression 2)
          {
               statement;
               ------
               ------
               expression 3;
           }    
      

Although the task of while and for loops is same, the for loop is generally used when the number of iterations are known in advance and while loop is used where number of iteration are not known.


Example 1.1:


/* Program to print the numbers from 1 to 10 using for loop*/
#include<stdio.h>
int main()
{
    int i;
   for(i = 1; i <= 10; i++)
   {
     printf("%d\t",i);
   }
   printf("\n");
    return 0;
}

Output:

 1       2       3       4       5       6       7       8       9       10

Nesting of loop:

When a loop is written inside the body of another loop, then it is known as nesting of loops. Any type of loop can be nested inside any other type of loop. For example a for loop may be nested inside another for loop or inside a while or do while loop. Similarly while and do while loops can be nested.

Example 1.1:


/* Program to understand nesting in for loop*/
#include <stdio.h>
int main()
{
  int i, j;
  for (i = 1; i <= 3; i++)    // outer loop
  {
    printf(" i = %d\n", i);
    for (j = 1; j <= 4; j++)   // inner loop
    {
      printf("j = %d\t", j);
    }
    printf("\n");
  }
  return 0;
}


Output:

   i = 1
   j = 1   j = 2   j = 3   j = 4
   i = 2
   j = 1   j = 2   j = 3   j = 4
   i = 3
   j = 1   j = 2   j = 3   j = 4

Here for each iteration of the outer loop, the inner loop is executed 4 times.


All the Programs Related to Loop are Given Below:

  1. C Program to Calculate the Power of a Number
  2. C Program to Print Factorial of a Number

*

إرسال تعليق (0)
أحدث أقدم