Chapter 7 Array C++, How to Program Deitel & Deitel Spring 2016 CISC 1600 Yanjun Li 1 Array Arrays are data structures containing related data items of same type. An array is a consecutive group of memory locations. Spring 2016 CISC 1600 Yanjun Li 2 1
Elements of An Array To refer to a particular location or element in the array, we specify the name of the array and the index of the element. The index must be integer or integer expression, its value must be larger than or equal to 0. First element has index zero. The element could be used as a variable. Example C[ 0 ] += 2; C[a+b] = 3; Spring 2016 CISC 1600 Yanjun Li 3 Example An array c has 12 elements ( c[0], c[1], c[11] ); the value of c[0] is 45. Spring 2016 CISC 1600 Yanjun Li 4 2
Declare An Array Declaration of an array: type arrayname[ arraysize ]; Example int c[ 12 ]; Array s size must be an integer constant greater than zero. Once declared, the size of the array is fixed. Arrays can be declared to contain values of data types like int, float, double, char, etc. Spring 2016 CISC 1600 Yanjun Li 5 Initialize An Array (1) With an initializer list Initializer list Items enclosed in braces ({}) and separated by commas. Examples int n[ 5 ] = { 10, 20, 30, 40, 50 }; int m[ 5 ] = { 10, 20, 30 }; The remaining elements are initialized to zero. int p[ ] = { 10, 20, 30, 40, 50 }; Because array size is omitted in the declaration, the compiler determines the size of the array based on the size of the initializer list. Spring 2016 CISC 1600 Yanjun Li 6 3
Initialize An Array (2) Using a loop to initialize the array s elements Declare array, specify number of elements Use repetition statement to loop for each element Example: int n[10]; for ( int i = 0; i < 10; i++) { n[ i ]=0; } Spring 2016 CISC 1600 Yanjun Li 7 Initialize An Array (3) Specifying an array s size with a constant variable and setting array elements with a loop statement. Example: const int arraysize = 10; int s[ arraysize ]; for (int i = 0; i < arraysize; i++) { s[ i ] = 2 + 2*i; } Spring 2016 CISC 1600 Yanjun Li 8 4
Initialize An Array (4) Read the value for each element one by one from the keyboard Example const int arraysize = 5; int array[arraysize]; for (int i=0;i<arraysize; i++) { cout << Please specify a value for element no. << i <<endl; cin >> array[i]; } Spring 2016 CISC 1600 Yanjun Li 9 Using An Array Usually use for loop to access each element of an array. C++ has no array bounds checking Referring to an element outside the array bounds is an execution-time logic error. It is not a syntax error. You need to provide the correct array size. Spring 2016 CISC 1600 Yanjun Li 10 5
Print An Array Use a for loop to access each element of the array and print one by one. Example const int arraysize = 5; int array[arraysize] = { 1, 2, 4, 67, 3 }; for (int i=0; i<arraysize; i++) { cout <<array[i]<<endl; } Spring 2016 CISC 1600 Yanjun Li 11 Using An Array Example 1 Summing the elements of an array Example: const int arraysize = 6; int a [ arraysize ] = { 87, 69, 45, 45, 43, 21 }; int total = 0; for ( int i = 0; i < arraysize; i++) { total += a[i]; } cout << Total of array elements is <<total<<endl; Spring 2016 CISC 1600 Yanjun Li 12 6
Using An Array Example 2 Using the counter as the index of elements of an array. Example const int arraysize = 5; double optionalequipmentcost [arraysize]; for (int i =0; i< arraysize; i++) { //for house No.? } //after the user selected engine and paint options, //save the optional equipment cost in an array. optionalequipmentcost[i] = optionalequipment; Spring 2016 CISC 1600 Yanjun Li 13 Using An Array Example 3 Using character arrays to store and manipulate strings We can store character strings in char arrays Can be initialized using a string literal Example char string1[] = "Hi"; Equivalent to Char string1[] = {'H', 'i'}; char string1[] = { 'H', 'i', '\0' }; Array contains each character plus a special stringtermination character called the null character ('\0') Spring 2016 CISC 1600 Yanjun Li 14 7
Using An Array Example 3 Using character arrays to store and manipulate strings (Cont.) Can also input a string directly into a character array from the keyboard using cin and >> cin >> string1; cin reads characters from the keyboard until the first white-space character is encountered regardless of the array size. cin >> may read more characters than the array can store A character array representing a null-terminated string can be output with cout and << cout << string1; Spring 2016 CISC 1600 Yanjun Li 15 Passing Arrays to Functions (1) Functions that take arrays as arguments: void modifyarray (int array [ ], int size); To pass an array argument to a function int hourlytemperatures[ 24 ]; modifyarray( hourlytemperatures, 24 ); Array size is normally passed as another argument so the function can process the specific number of elements in the array Spring 2016 CISC 1600 Yanjun Li 16 8
Passing Arrays to Functions (2) Arrays are passed by reference Function call actually passes starting address of array So function knows where array is located in memory Caller gives called function direct access to caller s data Called function can manipulate this data Spring 2016 CISC 1600 Yanjun Li 17 Passing Arrays to Functions (3) Example double kitchenoption(int, int []); int kitchenoptions[5]={0}; optionalfeaturecost = kitchenoption(counter, kitchenoptions); double kitchenoption(int counter, int oc[]) { //part of this function int choice; cin>>choice; oc[counter-1] = choice; } Spring 2016 CISC 1600 Yanjun Li 18 9
Passing An Element to Functions Individual array elements passed by value Use the subscripted name of the array element as an argument Single pieces of data Spring 2016 CISC 1600 Yanjun Li 19 const array parameters Qualifier const Example: void funcone(const int [ ]); int a[] = {10,20,30}; funcone(a); Prevent modification of array values in the caller by code in the called function Elements in the array are constant in the function body Enables programmer to prevent accidental modification of data Spring 2016 CISC 1600 Yanjun Li 20 10
Searching Arrays with Linear Search Arrays may store large amounts of data May need to determine if certain key value is located in an array Linear search Compares each element of an array with a search key Just as likely that the value will be found in the first element as the last On average, program must compare the search key with half the elements of the array To determine that value is not in array, program must compare the search key to every element in the array Works well for small or unsorted arrays Spring 2016 CISC 1600 Yanjun Li 21 Multidimensional Array Multidimensional arrays with two dimensions Called two dimensional or 2-D arrays Represent tables of values with rows and columns Elements referenced with two subscripts ([x][y]) In general, an array with m rows and n columns is called an m-by-n array Multidimensional arrays can have more than two dimensions Spring 2016 CISC 1600 Yanjun Li 22 11
Declaring & Initializing Two-Dimensional Arrays Declaring two-dimensional array b int b[ 3 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 1 and 2 initialize b[ 0 ][ 0 ] and b[ 0 ][ 1 ] 3 and 4 initialize b[ 1 ][ 0 ] and b[ 1 ][ 1 ] 0 and 0 initialize b[ 2 ][ 0 ] and b[ 2 ][ 1 ] (implicitly). Row 0 Row 1 Row 2 Column 0 1 3 0 Column 1 2 4 0 Spring 2016 CISC 1600 Yanjun Li 23 Two-Dimensional Array Spring 2016 CISC 1600 Yanjun Li 24 12
Passing Multidimensional Arrays to Functions Multidimensional array parameters Size of first dimension is not required As with a one-dimensional array Size of subsequent dimensions are required Compiler must know how many elements to skip to move to the second element in the first dimension Example void printarray( const int a[][ 3 ] ); Function will skip row 0 s 3 elements to access row 1 s elements (a[ 1 ][ x ]) Spring 2016 CISC 1600 Yanjun Li 25 Multidimensional-Array Manipulations Commonly performed with for statements Example Modify all elements in a row for ( int col = 0; col < 4; col++ ) a[ 2 ][ col ] = 0; Example Total all elements total = 0; for ( int row = 0; row < 3; row++ ) for ( int col = 0; col < 4; col++ ) total += a[ row ][ col ]; Spring 2016 CISC 1600 Yanjun Li 26 13
Reference Reproduced from the Cyber Classroom for C++, How to Program, 5/e by Deitel & Deitel. Reproduced by permission of Pearson Education, Inc. Spring 2016 CISC 1600 Yanjun Li 27 14