In the code below, can someone explain how the incrementing for the successive iterations results in the output? Thanks.

int main()
{
   using namespace std;
	 
   for (int i = 0; i < 3; i++)
   for (int j = 0; j < 3; j++)
                  
   cout << i << " " << j << endl;

   return 0;
}

Gives the ouput:

0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
Press any key to continue . . .

The first for loop is commonly called the outer loop and the second the inner loop and the two of them together are called a nested loop. Nested loops seldom go more than 3 deep, but can go deeper.

The outer loop says the first column can range from 0-2 and for each value of the first column the value of the second column can also range from 0-2. Or another way to look at it might be:

Outer loop i = 0
Inner loop:
j = 0
j = 1
j = 2
Outer loop i = 1
Inner loop:
j = 0
j = 1
j = 2
etc

The bahaviour would perhaps be more understandable if written like

int main()
{
   using namespace std;
   for (int i = 0; i < 3; i++)
   {
       for (int j = 0; j < 3; j++)
       {
           cout << i << " " << j << endl;
       }
    }
   return 0;
}

Thanks, it makes sense as a nested loop with the braces.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.