1
Computer Programming
Lecture 3 2 Dimensional & Multi Dimensional Arrays
8/24/2015
Outline
2- Dimensional Arrays
How to Initialize?
How to pass to Functions?
Multi- Dimensional
8/24/2015
Two - Dimensional Arrays
Multiple subscripts
a[ i ][ j ]
Tables with rows and columns
Specify row, then column
Array of arrays
a[1][4] is an array of 4 elements
a[0][0] is the first element of that array
Column 0
Column 1
Column 2
Column 3
Row 0
a[ 0 ][ 0 ]
a[ 0 ][ 1 ]
a[ 0 ][ 2 ]
a[ 0 ][ 3 ]
Row 1
a[ 1 ][ 0 ]
a[ 1 ][ 1 ]
a[ 1 ][ 2 ]
a[ 1 ][ 3 ]
Row 2
a[ 2 ][ 0 ]
a[ 2 ][ 1 ]
a[ 2 ][ 2 ]
a[ 2 ][ 3 ]
Column subscript
Array name
Row subscript
Two - Dimensional Arrays
To initialize
Default of 0
Initializers grouped by row in braces
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
1
3
Row 0
Row 1
2
4
1
3
0
4
Two - Dimensional Arrays
Referenced like normal
cout << b[ 0 ][ 1 ];
Outputs 0
1
3
0
4
Cannot reference using commas
cout << b[ 0, 1 ];
Syntax error
Function prototypes
Must specify sizes of column rows not necessary
void printArray( int [][ 3 ] );
// Initializing multidimensional arrays.
#include <iostream>
using namespace std;
Note the format of the
prototype.
void printArray( int [][ 3 ] );
int main()
{
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
cout << "Values in array1 by row are:" << endl;
printArray( array1 );
cout << "Values in array2 by row are:" << endl;
printArray( array2 );
cout << "Values in array3 by row are:" << endl;
printArray( array3 );
return 0; // indicates successful termination
} // end main
Note the various
initialization styles. The
elements in array2 are
assigned to the first row
and then the second.
// function to output array with two rows and three columns
For loops are often used to
iterate through arrays.
{
Nested loops are helpful
with multiple-subscripted
for ( int i = 0; i < 2; i++ ) { // for each row
for ( int j = 0; j < 3; j++ ) // output column values arrays.
void printArray( int a[][ 3 ] )
cout << a[ i ][ j ] << ' ';
cout << endl; // start new line of output
} // end outer for structure
} // end function printArray
Values in array1 by row are:
1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0