Need help understanding this code.

Anyone care to help me better understand the logic behind this code. Thanks a lot.

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
27
28
29
30
31
32
33
34
  	#include<iostream>

using namespace std;

int main()

{

	// Declare a 10x10 array

	const int numRows = 10;
	const int numCols = 10;

	int product[numRows][numCols] = { 0 };

	// Calculate a multiplication table

	for (int row = 0; row < numRows; ++row)
	for (int col = 0; col < numCols; ++col)
		product[row][col] = row * col;

	// Print the table

	for (int row = 1; row < numRows; ++row)

	{
		for (int col = 1; col < numCols; ++col)
			cout << product[row][col] << "\t";
		cout << endl;
	}

	return 0;

}
What is it you don't understand? The code is pretty straight forward.

Line 14: Declares a 2D array.

Line 20: Populates each cell with the product of the row number and the column number.

Lines 24-30: Prints out the contents of the 2D array.


I'm having trouble understanding line 20.

product[row][col] = row * col;

like how it forms the calculation. I think I just don't understand the math.

That statement simply multiplies row by col. For example 7 x 8. The result (for example 56) is stored in the array location indexed by [row][col].
This might confuse a bit, but the array product[numRows][numCols] is not going to use product[0][numCols] nor product[numRows][0].

That is why in the above code, even though the array is initialized as a 10x10 matrix, you only get to 9*9=81 in the lower right result.

0*n or n*0, although calculated, are never displayed in
1
2
3
4
5
6
for (int row = 1; row < numRows; ++row)
{
    for (int col = 1; col < numCols; ++col)
        cout << product[row][col] << "\t";
    cout << endl;
}

Increasing the values
1
2
const int numRows = 10; // try changing these two values to 13
const int numCols = 10;  // you will get to 12*12=144 maximum 
will also increase the size of the matrix.

If you instead increase the value, as shown below, because you want to get the "10th" row/column,
1
2
3
4
5
6
for (int row = 1; row < numRows + 1; ++row)
{
    for (int col = 1; col < numCols + 1; ++col)
        cout << product[row][col] << "\t";
    cout << endl;
}

you will get erroneous results.
This is called the fencepost error, or off-by-one error.
Some compilers warn you about undefined behavior in loop.

Of course, you can display the whole matrix like this:
1
2
3
4
5
6
for (int row =  0 ; row < numRows; ++row)
{
    for (int col =  0 ; col < numCols; ++col)
        cout << product[row][col] << "\t";
    cout << endl;
}

to include the first row and column of 0...
Topic archived. No new replies allowed.