How do you execute a nested for loop in C++?

Let’s start with a simple analogy. Imagine there are 3 lines at a concert, and each line has 5 people in it. For each line, you need to visit each person in that line. The rows are labeled as i and the columns as j.

How can we do this using for-loops?

Here comes the idea of using nested for loops. Using nested allows us to declare a for-loop within the body of another for-loop. The code below shows the syntax of the loop and explains it in detail.

#include <iostream>
using namespace std;
int main() {
int count=0;
for(int i=0;i<3;i++){
for(int j=0;j<5;j++){
count++;
}
}
cout<<"Total number of people: "<<count<<endl;
}

Within the for loop on line 6, another for loop is written in the body on line 8.

  1. In simple terms, the for loop on line 6 runs the for loop on line 8 for every value of i.
  2. The for loop on line 8 runs till the value of j increases from 0 to 4.
  3. Then it moves back to the for-loop on line 6.
  4. Steps 1 to 3 are repeated until the value of i is equal to 2.
  5. The loop on line 8 cannot run if the loop on line 6 terminates completely.

The slideshow below shows how this loop works when the value of i=0. This same process is repeated when i=1 and i=2.

Starting with the first row, i.e. i=0 and j=0
1 of 15

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved