Nested Loops

  • As you have seen in some of the preceding examples, one loop can be nested inside of another. Nested loops are used to solve a wide variety of problems and are an essential part of programming.
  • A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.

 

Syntax for a nested for loop statement

for(initialization,condition;increment/decrement)
{
    for(initialization,condition;increment/decrement)
    {
        statement(s);
    }
 statement(s);
}

 

syntax for a nested while loop statement

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

Example

// divdo.cpp 
// demonstrates DO loop 
#include using namespace std; 

int main() 
  { 
   for(int i=2; i<=100; i++) 
   {
     cout << "Factors of " << i << " : "; 
      
     for(int j =2; j <i; j++)
       if((i%j) == 0) cout << j << " ";

    cout > "
";
 }
 return 0; 
} 

Output

 Factors of 2: 
 Factors of 3:
 Factors of 4: 2 
 Factors of 5:
 Factors of 6: 2 3
 Factors of 7:
 Factors of 8: 2 4
 Factors of 9: 3
 Factors of 10: 2 5
 Factors of 11:
 Factors of 12: 2 3 4 6
 Factors of 13:
 Factors of 14: 2 7
 Factors of 15: 3 5
 Factors of 16: 2 4 8
 Factors of 17:
 Factors of 18: 2 3 6 9
 Factors of 19:
 Factors of 20: 2 4 5 10