Website For Developers

Nested Loop in C++



• A loop with in/inside a loop is called nested loop in C++.
• Any loop (for loop, while loop, do while loop) can be nested loop.
• For Example: a while loop can be nested in a for loop. and so on...
• There are 256 nesting levels are allowed in C++.


Syntax for nested for loop

for (initialization; condition; increment/decrement) {
  // outer-for loop body
  for (initialization; condition; increment/decrement) {
    // inner-for loop body
  }
}


Syntax for nested while loop

while (condition) {
  //Statements in outer while loop
  while (condition) {
    //Statements in inner while loop
  }
}


Syntax for nested do while loop

do {
  //Statements of outer loop body
  do {
    //Statements of inner loop body
  }
  while (condition);
}
while (condition);


Example of nested loop in C++

#include<iostream>
#include<conio.h>
using namespace std; int main() {

  int i, j;
  for (i = 1; i < 3; i++) {
    //body of outer loop starts

    for (j = 1; j <= 3; j++) {
      //body of inner loop starts
      cout<< "Value of Outer loop: "<< i<< "\t Value of Inner loop: "<< j<< endl;
    } //body of inner loop ends

    cout<< endl;
  } //body of outer loop ends
  getch();
  return 0;
}

Output

Value of Outer loop: 1     Value of Inner loop: 1
Value of Outer loop: 1     Value of Inner loop: 2
Value of Outer loop: 1     Value of Inner loop: 3

Value of Outer loop: 2     Value of Inner loop: 1
Value of Outer loop: 2     Value of Inner loop: 2
Value of Outer loop: 2     Value of Inner loop: 3


Explanation of the example

In the above example, there are two nested for loops. Outer loop is executes two time and inner loop executes three times with each iteration of outer loop. It means inner loop executes 2*3 = 6 times in total. When value of i = 1, the value of j changes from 1 to 3 in three iteration of inner loop. After that inner loop is terminates and cursor move back to outer loop. Then increment in outer loop value "i = 2" and again inner loop executes j times.


Example of different nested loop in C++

#include<iostream>
#include<conio.h>
int main() {

  int i, j = 1;
  while(j <= 2) {

    for (i = 1; j <= 2; i++) {
      cout<< "While loop "<< j<< " iteration and "<< "For loop "<< i<<" iteration"<< endl;
    }

    j++;
  }
  getch();
  return 0;
}

Output

While loop 1 iteration and For loop 1 iteration
While loop 1 iteration and For loop 2 iteration
While loop 2 iteration and For loop 1 iteration
While loop 2 iteration and For loop 2 iteration