C++ Nested Loops

C++ Nested Loops: In C++ nested loops are nothing but using a loop inside another loop is known as “Nested loops”.  C++ allows nearly 256 levels of testing.  Here, the no.of loops depend upon the complexity of the problem. Suppose if we are using a loop, outer loop with “m” number of times. So for each execution of the loop from 1….m, it executes m times. And there are different types of nested loops in C++.

C++ Nested Loops

The different types of nested loops in C++ are as follows:

  • Nested for loop
  • Nested while loop
  • Nested do-while loop

1) Nested for loop in C++

A for loop inside another for loop is known as “Nested for loop in C++“.

Syntax: of Nested for loop

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

C++ Nested For Loop

Example:

#include <iostream>
using namespace std;
int main () {
   int i, j;   
   for(i = 2; i<50; i++) {
      for(j = 2; j <= (i/j); j++)
         if(!(i%j)) break; // if factor found, not prime
         if(j > (i/j)) cout << i << " is prime\n";
   }  
   return 0;
}

Output:

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime

2) Nested While loop in C++

A while loop inside another while loop is known as “Nested While loop in C++“.

Syntax:

while (condition1)
{
statement(s);
while (condition2)
{
statement(s);
… … …
}
… … …
}

nested while loop c++

Example:

#include<iostream>
using namespace std;
int main()
{
   int i=0;
   
   while(i< 3)
   {
       int j = 0;
       while(j < 5)
       {
           cout<<"i = "<< i<<" and j=" <<j<<endl;
           j++;
       }
       i++;       
   }
   return 0;
}

Output:

i = 0 and j = 0
i = 0 and j = 1
i = 0 and j = 2
i = 0 and j = 3
i = 0 and j = 4
i = 1 and j = 0
i = 1 and j = 1
i = 1 and j = 2
i = 1 and j = 3
i = 1 and j = 4
i = 2 and j = 0
i = 2 and j = 1
i = 2 and j = 2
i = 2 and j = 3
i = 2 and j = 4

3) Nested do-while loop in C++

Using a do-while loop inside another do-while loop is known as “Nested do-while loop“.

Syntax:

do
{
statement(s);
do
{
statement(s);
… … …
}while (condition2);
… … …
}while (condition1);

 

Example:

#include <iostream>
using namespace std;
int main ()
{
  int i = 0;  
  do
  {
    int j= 0;
     do
     {
       cout << "i = " << i << " and j = " << j << endl;
       j++;
     }while(j < 5);
      i++;       
     }while(i < 3);  
   return 0;
}

Output:

i = 0 and j = 0
i = 0 and j = 1
i = 0 and j = 2
i = 0 and j = 3
i = 0 and j = 4
i = 1 and j = 0
i = 1 and j = 1
i = 1 and j = 2
i = 1 and j = 3
i = 1 and j = 4
i = 2 and j = 0
i = 2 and j = 1
i = 2 and j = 2
i = 2 and j = 3
i = 2 and j = 4