Multi
Dimensional Arrays
Much of the data computers process is stored in the
form of tables.
Hours worked/week |
||||
Employee # |
Week 1 |
Week 2 |
Week 3 |
Week 4 |
1 |
10 |
10 |
15 |
15 |
2 |
25 |
27 |
26 |
28 |
3 |
30 |
30 |
30 |
30 |
4 |
40 |
45 |
42 |
41 |
5 |
40 |
35 |
35 |
35 |
Tables have rows and columns. Columns are vertically arranged data, and
rows are horizontally arranged data.
How can we represent the data in the table in C++?
We can use 5 different arrays, but do we arrange
these by Employee or by week?
C++ allows us to represent table data as a two
dimensional array. The rows and columns
have a matrix structure.
column row |
0 |
1 |
2 |
3 |
0 |
0,0 10 |
0,1 10 |
0,2 15 |
0,3 15 |
1 |
1,0 25 |
1,1 27 |
1,2 26 |
1,3 28 |
2 |
2,0 30 |
2,1 30 |
2,2 30 |
2,3 30 |
3 |
3,0 40 |
3,1 45 |
3,2 42 |
3,3 41 |
4 |
4,0 40 |
4,1 35 |
4,2 35 |
4,3 35 |
To declare a 2 dimensional array for the table:
int hoursperweek [5][4];
Alternately:
int rows =
5;
int columns
= 4;
int hoursperweek [rows][columns];
In general:
datatype arrayname
[numberrows][numbercolumns];
We can initialize two dimensional arrays in the
declaration.
char
ticTacToeBoard[3][3] = {{'x', 'x', 'o'},
{'o', 'o', 'x'},
{'x', 'o', ' '}
};
int A[3][4] = {8, 2, 6, 5}, //row 0
6, 3, 1 ,0, //row 1
8, 7, 9, 6}; //row 2
Problem: The
employee table is stored in a file.
1. Read
the values into a 2 dimensional array
2. Print:
a. The
average hours worked per week
b. The
average number of hours worked per employee
Three dimensional arrays
const int
rows = 3;
const int
columns = 4;
const int
rank = 2;
int dim3
[rows][columns][rank]
Need 3 loops to process a three dimensional array.
Need n loops to process an n dimensional array.