C++ Nested loops



When we write any loop statement within the another loop statement then that structure is called as nested loop. We have already seen all the loops statements (while loop, do..while loop, for loop)

Nesting of the loops :

Consider the following syntax of the nested loops –

for(initialize; condition; increment)
{
   for (initialize; condition; increment)
   {
      statement(s);
   }
   statement(s); 
}

OR

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

OR

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

}while( condition );

However we can use any combination of the loops in order to achieve nested loop structure.

Example of nested loop :

In this example we need to print all the combinations of the digits from 0 to 5. i.e 11,23 or 05

#include <iostream>
using namespace std;
 
int main ()
{
   int i, j;
   
   for(i=0; i<=5; i++) {

      for(j=0; j <= 5; j++) {
        cout << i << j <<" \t";
      }

   cout <<"\n";
   }

   return 0;
}

Output :

00 01 02 03 04 05
10 11 12 13 14 15
20 21 22 23 24 25
30 31 32 33 34 35
40 41 42 43 44 45
50 51 52 53 54 55

Explanation of the program :

In the outer for loop when the value of i becomes 0 then control enters into the inner loop where j will take value from 0 to 5 considering the same value of i = 0

Value of i Value of j in inner loop
i = 0 Consider j = 0 1 2 3 4 5
i = 1 Consider j = 0 1 2 3 4 5
i = 2 Consider j = 0 1 2 3 4 5
i = 3 Consider j = 0 1 2 3 4 5
i = 4 Consider j = 0 1 2 3 4 5
i = 5 Consider j = 0 1 2 3 4 5