Prefix vs Postfix and table made of array?

208 Views Asked by At

Can you please explain this code, keeping in mind that the person who wrote it was using it to teach me the difference between prefix and postfix incrementations

int main()
{
    const int ROWS = 3;`enter code here`
    const int COLUMNS = 3;`enter code here`
    char board[ROWS][COLUMNS] = {{'O', 'X', 'O'}, {' ', 'X', 'X'}, {'X', 'O', 'O'}};
    cout << "Here’s the tic-tac-toe board:\n";




    int i = 0;
    int j = 0;
    while ( i < ROWS) {
        cout<<board[i][j];

        j++;

        if (j >= COLUMNS) {
            j = 0;
            i++;
            cout << endl;
        }
    }

}
1

There are 1 best solutions below

2
On BEST ANSWER

The code doesn't seem to show any difference between postfix and prefix incrementation, anyway this is how it works:

POSTFIXED

int x = 10;
cout<< (x++); //output: 10
//now x is 11

PREFIXED

int x = 10;
cout<< (++x); //output: 11 (and x is already 11)

Basically, the postfixed increment will only show its effects after the operation where it is called. The prefixed increment will shot its effect immediatly, so that the incremented value is already used in the command where it is called.

If the increment is isolated, that is, not used inside an operation, it's basically the same thing:

for(int i = 0; i < 10; i++)   =   for(int i = 0; i < 10; ++i)

About your code, it just walks through all slots of the matrix in this order:

(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)

When j >= COLUMNS, it means that (0,0), (0,1), (0,2) were already visited, so you can go to the next row by doing i++ (i represents the row index) because all the columns of row i were already visited. Doing j = 0 resets the column to the beginning (j represents the column index).