Array Question Answers

Question a

An array with five rows and three columns. The illustration adds the array's dimensions: 5 rows and 3 columns.

A variable definition consists of a data type and a variable name. The definition of an array has both parts plus the size of each array dimension. The array in the question has 5 rows and 3 columns, so the correct definition is:

int scores[5][3];

Question b

An array with five rows and three columns. The element in the fourth row and the second column is colored blue. The illustration adds the row and column index numbers: 0-4 rows and 0-2 columns.

Recall that each array dimension is zero-indexed, so valid index values are always in the range of 0..size-1. Specify the row first and then column:

scores[3][1]

An array element is just a single variable and may be used wherever a variable of that type is legal. So, for example, the following are all valid uses of the expression representing the shaded element:

scores[3][1] = 100;
double x = scores[3][1] / total;
cout << scores[3][1] << endl;

Question c

It's easy to define and to initialize non-array variables in a single statement: int max = 50;. However, initializing arrays in the same statement that defines them requires a different notation, which the text introduces later in this chapter. So, the correct answer to the question is:

scores[3][1] = 50;
Error

There is a problem with trying to define an array and to initialize an element in the interior of the array in a single statement: int scores[3][1] = 50;. The first part of the statement, int scores[3][1], creates an array with 3 rows and 1 column, which, because arrays are zero-indexed, makes the array element scores[3][1] out of bounds.