Todayโs Outline
Array Definition
Array Initialization
Passing Arrays to Function
Array Operations
Multi-Dimensional Array
Array Definition
// must be declared with constant integer
int mark[ 10 ];
// doesn't work
int v;
int mark[v];
Array Initialization
// Basic Initialization
int a[ 3 ] = { 1 , 2 , 3 }; // {1, 2, 3}
// Initialization without Size
int b[] = { 1 , 2 , 3 }; // {1, 2, 3}
// Partial Initialization
int c[ 5 ] = { 1 , 2 , 3 }; // {1, 2, 3, 0, 0}
// Initialization to All Zeros
int d[ 3 ] = { 0 }; // {0, 0, 0}
Initialization of Char Arrays
char str[ 3 ] = { 'a' , 'b' , 'c' };
char str[ 3 ] = "abc" ;
char str[] = "abc" ; // char[4] {'a', 'b', 'c', '\\0'}
Passing Arrays to Function
void func ( int a []) {
cout << a[ 0 ] << endl; // print 1
a[ 0 ] = 10 ;
}
void main () {
int a[ 3 ] = { 1 , 2 , 5 };
func (a);
cout << a[ 0 ] << endl; // print 10
}
Array Operations
sizeof
cout << sizeof ( int ); // 4
int a[ 4 ];
cout << sizeof (a); // 16
Compare two arrays
int main () {
int array1[ 5 ] = { 10 , 5 , 3 , 5 , 1 };
int array2[ 5 ];
cout << "input 5 elements to array2" << endl;
for ( int i = 0 ; i < 5 ; i ++ ) {
cin >> array2[i];
}
bool arrayEqual = true ;
for ( int i = 0 ; i < 5 && arrayEqual; i ++ ) {
if (array1[i] != array2[i]) {
arrayEqual = false ;
}
}
if (arrayEqual) {
cout << "The arrays are equal" << endl;
} else {
cout << "The arrays are not equal" << endl;
}
return 0 ;
}
Sort
Slow but easy to code
Selection sort
Bubble sort
Insertion sort
Faster but more complex to code
Quick sort
Merge sort
Heap sort
Search
Multi-Dimensional Array
Array with more than one index
Stored in the row-major
order
2D Array Initialization
int page[ 2 ][ 3 ] = {{ 1 , 2 , 3 },{ 4 , 5 , 6 }};
int page[ 2 ][ 3 ] = { 1 , 2 , 3 , 4 , 5 , 6 };
int page[ 2 ][ 3 ] = {{ 1 },{ 4 , 5 }}; = {{ 1 , 0 , 0 },{ 4 , 5 , 0 }}
int page[][ 3 ] = { 1 , 2 , 3 , 4 , 5 , 6 };
int page[ 2 ][] = { 1 , 2 , 3 , 4 , 5 , 6 }; // compile error
Passing 2D Array to Function
void sort2D ( int x [][ 10 ]) { // 1st dimension is optional, 2nd must be given
// ...
}
void main () {
int y[ 20 ][ 10 ];
sort2D (y);
}