Friday, December 8, 2017

Nested Loop In C Programming

One loop inside another loop is called Nested loop. Here we will discuss about this.

Syntax of a Nested for loop


for ( variable initialization ;  condition ;  variable update )
{
      for ( variable initialization ;  condition ;  variable update )
      {
          // body statement.
      }
}


Example of a Nested for loop. This program will print “Outer Loop” 3 times. After every time it will print “Inner Loop” 2 times.


#include <stdio.h>

int main() 
{
     for(int i = 1;  i <= 3;  i++)
     {
           printf( “%d. Outer Loop \n”, i );
           for(int j = 1;  j <= 2;  j++)
           {
                 printf ( " Inner Loop \n", j );
           }
           printf(“ \n ”);
     }
     return 0;
}

Output

1. Outer Loop
Inner Loop
Inner Loop

2. Outer Loop
Inner Loop
Inner Loop

3. Outer Loop
Inner Loop
Inner Loop

Note : We can use any loop inside any other loop. For an example we can use while loop inside a for loop or vice versa.



Previous Topic

Next Topic



No comments:

Post a Comment