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.
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.
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.
RELATED TAGS
View all Courses