Professional Documents
Culture Documents
CSCI 230
Arrays
Multidimensional Arrays
Dale Roberts, Lecturer
IUPUI
droberts@cs.iupui.edu
Dale Roberts
Multiple-Dimensional Arrays
2D Arrays
A[0]: 1D array
1-Dimensional vector
A[0][0]: (2 subscripts)
2D array (matrix)
2-dimensional vector
Row 0
Row 1
Row 2
a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column subscript
Array
name Row subscript
Dale Roberts
Multiple-Subscripted Arrays
Initialization
3
4
int b[2][2] = {{ 1, 2 }, { 3, 4 } };
int c[3][2] = {{ 1, 2 }, { 3, 4 }, { 5, 6 }};
1
Referencing elements
Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
Dale Roberts
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
Initialize variables
Define functions to take double
scripted arrays
Dale Roberts
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
return lowGrade;
}
/* Find the maximum grade */
int maximum( const int grades[][ EXAMS ],
int pupils, int tests )
{
int i, j, highGrade = 0;
for ( i = 0; i <= pupils - 1; i++ )
for ( j = 0; j <= tests - 1; j++ )
if ( grades[ i ][ j ] > highGrade )
highGrade = grades[ i ][ j ];
return highGrade;
}
/* Determine the average grade for a particular exam */
double average( const int setOfGrades[], int tests )
{
Dale Roberts
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
int i, total = 0;
for ( i = 0; i <= tests - 1; i++ )
total += setOfGrades[ i ];
return ( double ) total / tests;
}
/* Print the array */
void printArray( const int grades[][ EXAMS ],
int pupils, int tests )
{
int i, j;
printf( "
[0]
[1]
[2]
Define function
[3]" );
Program Output
[0]
studentGrades[0] 77
studentGrades[1] 96
studentGrades[2] 70
[1]
68
87
90
[2]
86
89
86
[3]
73
78
81
Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75
Dale Roberts