Two Dimensional Arrays

advertisement
Two-Dimensional Data
• Class of 5 students
• Each student has 3 test scores
• Store this information in a twodimensional array
• First dimension: which student 0,
1, 2, 3 or 4
• Second dimension: which test
score 0, 1, or 2
Declaring a 2D Array
• Give a second pair of square
brackets to tell C++ you want a 2D
array
• Example:
int grades[5][3];
Creating a 2D Array
• Create array elements by telling how
many ROWS and COLUMNS
• Example:
int grades[5][3];
grades is a two-dimensional array, with 5
rows and 3 columns.
One row for each student. One column
for each test.
C++ arrays are row major, which means
that we always refer to the row first.
Initializing Elements
// First student scores
grades[0][0] = 78;
grades[0][1] = 83;
grades[0][2] = 82;
Write assignment statements to
fill-in the rest of the array.
Declare & Create & Initialize
Short Cut
• Example:
int grades[5][3] =
{ { 78, 83, 82 },
{ 90, 88, 94 },
{ 71, 73, 78 },
{ 97, 96, 95 },
{ 89, 93, 90 } };
A Two-D Array is an array of arrays.
Each row is itself a One-D array.
Row, Column Indices
0
1
2
0 78
83
82
1 90
88
94
2 71
73
78
3 97
96
95
4 89
93
90
Give both the ROW and COLUMN indices to pick out an
individual element.
The fourth student’s third test score is at ROW 3,
COLUMN 2
What are the elements of the array table?
int table[3][4];
x = 1;
for (row = 0; row < 3; row++)
for (col = 0; col < 4; col++)
{
table[row][col] = x;
x++;
} //for col
column
row
Exercise: Average Overall
• Find the average test score of all
students’ test scores.
• Use rows to tell you how many
rows in the 2D array.
• Use cols to tell you how many
columns in the 2D array.
Exercise: Average Overall
int sum = 0;
for(int r = 0; r < rows; r++)
for(int c = 0; c < cols; c++)
sum = sum + grades[r][c];
int avg = sum / (rows*cols);
• Write a function that prints out the
elements in a 2-D array (as they
appear in the matrix)
Exercise: print 2-D array
void printArray(int matrix[][])
{
for(int i = 0; i < matrix.length; i++)
{
for(int j = 0; j < matrix[0].length; j++)
cout << (matrix[i][j] << ” “);
cout << endl;
}
}
• Write a function that returns the
maximum element in a 2-D array.
• Things work pretty much the same
way with 3-D arrays (and 4-D and
…)
Exercise: find maximum
in a 2D array
int findMax(int matrix[][COLS], int r, int
c)
{
int max = matrix[0][0];
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
if ( matrix[i][j] > max)
max = matrix[i][j];
return max;
}
Download