Nesting for loops.

If I typed it out right, the program below displays:
0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2
3,0 3,1 3,2
4,0 4,1 4,2
However, I don't understand why 'i' doesn't increment with each pair. After both loops, it seems to me like ++i in the first loop should produce 0,0 1,1 2,2.
Why doesn't it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main()
{
cout << "counting with nested for loops: ";
const int ROWS = 5;
const int COLUMNS =3;
for (int i = 0; i < ROWS; ++i)
    {
        for (int j = 0; j < COLUMNS; ++j)
        {
            cout << i << "," << j << "  ";
        }
        cout << endl;
    }
system ("pause"); /*the book doesn't do this, but I do so I can look at the results.
Am I doing something wrong or unprofessional?*/
return 0;
}
Last edited on
Each iteration of i produces (COLUMNS) number of iterations of the inner for-loop.
The values of i are: 0, 1, 2, 3, 4
The values of j are: 0, 1, 2

If you have 5 values for i and for each iteration of the i for-loop, you have 3 iterations of the j for-loop, then it makes sence that you will have 15 values in the end and if you print the values of i and j at each iteration, then the only values you can get are the ones that the program produced


Post increment and pre increment have no impact on the values being displayed. Even if you were to change it to i++ and j++, the same values will still be printed
Topic archived. No new replies allowed.