Why does this work?

I've been having trouble understanding for statements. So, playing around a little, I wanted to display a multi-dimensional array. It works, but there's something that I don't get.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

int main()
{
    char board[9][10] = { {'.', '.', '.', '.', '.', '.', '.', '.', '.', 'n'},
                          {'.', '.', '.', '.', '.', '.', '.', '.', '.', 'n'},
                          {'.', '.', '.', '.', '.', '.', '.', '.', '.', 'n'},
                          {'.', '.', '.', '.', '.', '.', '.', '.', '.', 'n'},
                          {'.', '.', '.', '.', '.', '.', '.', '.', '.', 'n'},
                          {'.', '.', '.', '.', '.', '.', '.', '.', '.', 'n'},
                          {'.', '.', '.', '.', '.', '.', '.', '.', '.', 'n'},
                          {'.', '.', '.', '.', '.', '.', '.', '.', '.', 'n'},
                          {'.', '.', '.', '.', '.', '.', '.', '.', '.', 'n'}};
    int i;
    int j;
    for (i = 0; i < 9; i ++)
    {
        for (j = 0; j < 10; j++)
        {
            cout<< board[i][j];
        }
    }
    return 0;
}


How is it that the for (i = 0; i < 9; i ++) doesn't end before accomplishing for (j = 0; j < 10; j++). I know that it prints what I want, nine periods to a line, then moves to a new line and prints nine more until there are nine lines of nine periods. So am I doing something wrong or am I miss understanding it?

NOTEThe newline characters aren't showing up properly in the post, but they are right.
That's because those aren't newline characters. A newline character is n. (Whoops. The forum's parser removes the backslash.)
The way this works is that on iteration 1 of the outer loop, the inner loop executes itself 10 times. Then it moves on to iteration 2 of the outer loop, which repeats that.
Last edited on
Okay, that makes a lot of sense.

Thank you very much.
Also, as an alternative to putting newline characters at the end of your rows, do something like this...

1
2
3
4
5
6
7
8
9
10
11
for(int i = 0;i < 10;i++)
{
    for(int j = 0;j < 10;j++)
    {
        cout << array[i][j];
        if(((j + 1)%9) == 0)
        {
            cout << endl;
        }
    }
}
Last edited on
Topic archived. No new replies allowed.