# 1

Chapter 4 - Arrays
Outline 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays Case Study: Computing Mean, Median and Mode Using Arrays Searching Arrays: Linear Search and Binary Search Multiple-Subscripted Arrays Thinking About Objects: Identifying a Class's Behaviors

2

4.1  Arrays

Introduction

± Structures of related data items ± Static entity - same size throughout program

 A few types
± C-like, pointer-based arrays ± C++, arrays as objects

3

4.2  Array

Arrays

± Consecutive group of memory locations ± Same name and type

 To refer to an element, specify
± Array name and position number

 Format: arrayname[ position number ]
± First element at position 0 ± n element array c:
c[ 0 ], c[ 1 ]«c[ n - 1 ]

 Array elements are like normal variables
c[ 0 ] = 3; cout << c[ 0 ];

 Performing operations in subscript. If x = 3,
c[ 5 ± 2 ] == c[ 3 ] == c[ x ]

2 Name that this same Arrays of array (Note all elements of array have the name. All rights reserved. c) -45 6 0 72 1543 -89 0 62 -3 1 6453 78 c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c  2000 Prentice Hall. Inc. .4 4.

 2000 Prentice Hall. x[ 27 ]. .5 4.specify: Name Type of array Number of elements Examples int c[ 10 ]. Inc. All rights reserved.3 ± ± ± ± Declaring Arrays  Declaring arrays .  Declaring multiple arrays of same type ± Similar format as other variables ± Example int b[ 100 ]. float hi[ 3284 ].

therefore n is a 5 element array  2000 Prentice Hall. 2.6 4. 5 }. 2. the initializers determine it int n[] = { 1. rightmost elements become 0 ± If too many initializers. a syntax error is generated int n[ 5 ] = { 0 } ± Sets all the elements to 0  If size omitted. 3.4  Initializers Examples Using Arrays int n[ 5 ] = { 1. . 3. 5 }. 4. All rights reserved. 4. ± If not enough initializers. Inc. ± 5 initializers.

Define loop 3. cout << "Element" << setw( 13 ) << "Value" << endl. 14. Initialize array using a declaration int main() { int n[ 10 ] = { 32. for ( int i = 0. Print out each array element Element Value 0 32 1 27 2 64 3 18 4 95 5 14 6 90 7 70 8 60 9 37  2000 Prentice Hall.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // Fig. 70. Inc. 18. 60. i++ ) cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl. using std::endl. #include <iomanip> using std::setw. 64. 7 Outline 1. 95. 4. 2. 27. 90. Program Output . 37 }. All rights reserved. i < 10. return 0.cpp // Initializing an array with a declaration #include <iostream> using std::cout.4: fig04_04. } Notice how they array is declared and elements referenced.

7: fig04_07. 2.1 2 3 4 5 6 7 8 9 10 // Fig.cpp 8: Cannot modify a const object in function main() *** 2 errors in Compile *** Program Output  2000 Prentice Hall. // Error: x must be initialized x = 7. All rights reserved.cpp // A const object must be initialized 8 Outline 1. 11 } Fig04_07.cpp: Error E2304 Fig04_07. 4. Initialize const variable int main() { const int x. Attempt to modify variable return 0. // Error: Notice that const variables must be cannot modify a const cannot be modified initialized because they variable later.cpp 6: Constant variable 'x' must be initialized in function main() Error E2024 Fig04_07. . Inc.

. All rights reserved. ± Takes user input ± Side effect: if too much text entered. data written beyond array  2000 Prentice Hall.4  Strings Examples Using Arrays ± Arrays of characters ± All strings end with null ('\0') ± Examples: char string1[] = "hello". 'l'. char string1[] = { 'h'. ± Subscripting is the same as for a normal array String1[ 0 ] is 'h' string1[ 2 ] is 'l'  Input from keyboard char string2[ 10 ].9 4. 'l'. Inc. cin >> string2. 'e'. 'o'. '\0¶ }.

4_12: fig04_12. } Enter a string: Hello there string1 is: Hello string2 is: string literal string1 with spaces between characters is: H e l l o string1 is: there  2000 Prentice Hall. All rights reserved.cpp // Treating character arrays as strings #include <iostream> using std::cout. cout << "Enter a string: ". return 0. cout << "string1 is: " << string1 << "\nstring2 is: " << string2 << "\nstring1 with spaces between characters is:\n". elements are referenced like arrays. 10 Outline Inputted strings are separated by whitespace characters. // reads "there" cout << "\nstring1 is: " << string1 << endl. int main() { char string1[ 20 ]. Inc. cin >> string1. "there" stayed in the buffer. i++ ) cout << string1[ i ] << ' '. Initialize strings 2. 1.2 Print characters individually 2. cout << endl.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 // Fig.3 Input string Notice how string Print string 3. using std::endl. using std::cin. Print strings 2. for ( int i = 0. string2[] = "string literal". Program Output .1 Define loop 2. cin >> string1. string1[ i ] != '\0'.

11 4. to function myFunction. myArray[ 3 ]) to function  2000 Prentice Hall. ± Array size is usually passed to function  Arrays passed call-by-reference ± Value of name of array is address of the first element ± Function knows where the array is stored  Modifies original memory locations  Individual array elements passed by call-by-value ± pass subscripted name (i.5 Passing Arrays to Functions  Specify the name without any brackets ± To pass array myArray declared as int myArray[ 24 ]. Inc. . a function call would resemble myFunction( myArray. All rights reserved.. 24 ).e.

int arraySize ).5 Passing Arrays to Functions  Function prototype: void modifyArray( int b[]. All rights reserved. ± Parameter names optional in prototype  int b[] could be simply int []  int arraysize could be simply int  2000 Prentice Hall. Inc. .12 4.

cout << Hall. cout << endl. using std::endl. int i.14: fig04_14. int ). Individual array elements are not modified by default. 2. { const int arraySize = 5.cpp // Passing arrays and individual array elements to functions #include <iostream> using std::cout. All rights reserved. Modify the array (call by reference) No parameter names int main() function prototype. a[ arraySize ] = { 0. 4. in cout << "Effects of passing entire array call-by-reference:" << "\n\nThe values of the original array are:\n".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 // Fig. 3. values of the modified array are:\n". The values of the original array are: 0 1 2 3 4 The values of the modified array are: 0 2 4 6 8  2000 Prentice "TheInc. void modifyArray( int []. #include <iomanip> using std::setw. // appears strange 1. i < arraySize. arraySize ). 13 Outline 1. 1. . i++ ) cout << setw( 3 ) << a[ i ].1 Initialize arrays 2. 4 }. void modifyElement( int ). // array a passed call-by-reference modifyArray( a. Define function to take in arrays Functions can modify entire arrays. for ( i = 0.

i++ ) cout << setw( 3 ) << a[ i ]. void modifyArray( int b[]. } Outline 2.1 Function Definitions Parameter names required in function definition // In function modifyArray. void modifyElement( int e ) { cout << "Value in modifyElement is " << ( e *= 2 ) << endl. cout << "The value of a[3] is " << a[ 3 ] << endl. modifyElement( a[ 3 ] ). j < sizeOfArray. int sizeOfArray ) { Effects of passing array element call-by-value: for ( int j = 0.32 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 14 for ( i = 0. i < arraySize. Print changes. "e" is a localThe value of a[3] is 6 copy of // array element a[ 3 ] passed from main. 3. "b" points to the original // array "a" in memory. Inc. The value of a[3] is 6 } Value in modifyElement is 12 // In function modifyElement.1 Modify an element (call by value) 3. } . return 0. j++ ) b[ j ] *= 2.  2000 Prentice Hall. cout << "\n\n\n" << "Effects of passing array element call-by-value:" << "\n\nThe value of a[3] is " << a[ 3 ] << '\n'. All rights reserved.

. All rights reserved. Inc.15 Effects of passing entire array call-by-reference: The values of 0 1 2 3 The values of 0 2 4 6 the original array are: 4 the modified array are: 8 Outline Program Output Effects of passing array element call-by-value: The value of a[3] is 6 Value in modifyElement is 12 The value of a[3] is 6  2000 Prentice Hall.

.6  Sorting data Sorting Arrays ± Important computing application ± Virtually every organization must sort some data  Massive amounts must be sorted  Bubble sort (sinking sort) ± Several passes through the array ± Successive pairs of elements are compared  If increasing order (or identical). All rights reserved. elements exchanged ± Repeat these steps for every element  2000 Prentice Hall. no change  If decreasing order.16 4. Inc.

6  Example: ± ± ± ± Sorting Arrays Original: 3 4 2 6 7 Pass 1: 3 2 4 6 7 Pass 2: 2 3 4 6 7 Small elements "bubble" to the top  2000 Prentice Hall. All rights reserved. Inc.17 4. .

3. Inc. All rights reserved. Median and Mode Using Arrays  Mean ± Average 4. 1. 4.18 Case Study: Computing Mean. 4. 3.7  Median ± Number in middle of sorted list ± 1. 1. 2. 2. 5 (3 is median)  Mode ± Number that occurs most often ± 1. 5 (1 is mode)  2000 Prentice Hall. . 3.

mode( int []. 9. 7. 7. 8. 9. 6. Function prototypes 1. 9. 8. Inc. 6. int ). 7. 9. 3. 3. All 2. 7. 4. 8. 9. and mode of the data. 4. printArray( const int[]. 9. 5. 8. bubbleSort( int[]. int frequency[ 10 ] = { 0 }. 5. void void void void void mean( const int []. rights reserved. 7. int ). 9. 9. 8. int ). 9. 8. 8. 8. and mode int main() { const int responseSize = 99. 8. 8. 7.  2000 Prentice Hall. 8. 9. // It computes the mean. 8. median. 7. int ). 7. 4. 7. 3. using std::ios. using std::setprecision. 8. 7. response[ responseSize ] = { 6. int []. 8. #include <iostream> using std::cout. 9. using std::setiosflags. 9. 8. 9. 7. 5. 9. 2. median( int []. int ). 6. 7. 7. 5. 8. 19 Outline 1. 8. #include <iomanip> using std::setw. Call functions mean. 9.1 Initialize array 2.17: fig04_17. . 7. 8. 9. median. using std::endl. 7. 6. 7.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 33 // Fig. 8.cpp // This program introduces the topic of survey data analysis. 8. 9. 8.

4. 5. cout << "********\n Mean\n********\n". 8. 8. 5. 8. 7. 7. The mean is equal to the total of\n" "all the data items divided by the number\n" "of data items (" << arraySize "). } void mean( const int answer[]. 20 Outline 3. responseSize ). 7 }. 7. j < arraySize. mode( frequency. All rights Median\n********\n" "The mean is the average value of the data\n" "items. The mean value for\nthis run is: " total << " / " << arraySize << " = " setiosflags( ios::fixed | ios::showpoint ) setprecision( 4 ) static_cast< double >( total ) / arraySize << "\n\n". Inc. j++ ) total += answer[ j ]. 2. 6. Define function mean 3. 5. . responseSize ). 9. 6. int size ) {  2000 Prentice "\n********\n reserved. responseSize ). 7. 6. cout << << << << << << << << << } void median( int answer[]. 1. 5. int arraySize ) { int total = 0.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 65 66 67 7. response. 6. mean( response.1 Define function median for ( int j = 0. 7. cout << Hall. 8. return 0. median( response. 9. 3. 4. 8. 8. 4.

All rights reserved. int size ) 81 { 82 83 84 85 86 87 88 89 90 91 92 93 94 for ( int j = 0.\nFor this run the median is " << answer[ size / 2 ] << "\n\n". 0 5 0 .1.1. 5\n\n". int rating. 3. cout << "\n********\n Mode\n********\n".1 Increase frequency[] depending on response[] Notice how the subscript in frequency[] is the value of an element in response[] (answer[]). << Hall. rating <= 9. bubbleSort( answer. largest = 0. size ). cout << "Response"<< setw( 11 ) << "Frequency" << setw( 19 ) << "Histogram\n\n" << setw( 55 ) << "1 1 2 2\n" << setw( 56 ) 95  2000 Prentice "5 Inc. 21 Outline printArray( answer. cout << "\n\nThe median is element " << size / 2 << " of\nthe sorted " << size << " element array. rating++ ) freq[ rating ] = 0.2 Print middle element 80 void mode( int freq[].2. printArray( answer. int answer[]. cout << "\n\nThe sorted array is". modeValue = 0. for ( rating = 1.1 Define function median 3. size ).2 Define function mode 3. 3. size ).68 69 70 71 72 73 74 75 76 77 78 } 79 << "The unsorted array of responses is". j++ ) ++freq[ answer[ j ] ].1 Sort Array 3. j < size.

. h <= freq[ rating ]. 22 Outline 3. modeValue = rating. rating++ ) { cout << setw( 8 ) << rating << setw( 11 ) << freq[ rating ] << " ". } if ( freq[ rating ] > largest ) { largest = freq[ rating ]. cout << "The mode is the most frequent value. int size ) 118{ 119 int hold. h++ ) cout << '*'. } cout << '\n'.96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115} 116 117void bubbleSort( int a[]. for ( rating = 1." << endl. Inc. All rights reserved. rating <= 9.\n" << "For this run the mode is " << modeValue << " which occurred " << largest << " times.3 Define bubbleSort Print stars depending on value of frequency[] 120 2000 Prentice Hall. for ( int h = 1.

All rights reserved.3 Define printArray Bubble sort: if elements out of order.1. j < size . a[ j ] = a[ j + 1 ]. for ( int j = 0. if ( j % 20 == 0 ) cout << endl.  . a[ j + 1 ] = hold. } 132void printArray( const int a[]. Inc. int size ) 133{ 134 135 136 137 138 139 140 } cout << setw( 2 ) << a[ j ]. j++ ) 3.121 122 123 124 125 126 127 128 129 130} 131 for ( int pass = 1. pass < size. swap them. j < size. pass++ ) 23 Outline for ( int j = 0. j++ ) { 141} 2000 Prentice Hall. if ( a[ j ] > a[ j + 1 ] ) { hold = a[ j ].3 Define bubbleSort 3.

All rights reserved. Inc. The mean is equal to the total of all the data items divided by the number of data items (99). For this run the median is 7  2000 Prentice Hall.8788 24 Outline 4. Program Output ******** Median ******** The unsorted 6 7 8 9 8 7 6 7 8 9 3 9 6 7 8 7 8 7 5 6 7 2 5 3 7 4 4 2 5 3 The sorted 1 2 2 2 3 5 6 6 6 6 7 7 7 7 7 8 8 8 8 8 9 9 9 9 9 array 8 9 8 8 7 8 9 8 9 9 4 6 8 7 5 of responses is 9 7 8 9 5 9 8 7 7 7 8 9 8 9 8 9 2 7 8 9 8 9 8 9 4 7 8 9 6 8 7 8 6 4 5 6 1 6 5 7 8 7 7 9 8 7 8 5 7 7 8 9 3 8 array 3 3 3 6 6 6 7 7 7 8 8 8 9 9 9 is 4 4 6 6 7 7 8 8 9 9 4 7 7 8 9 4 7 7 8 9 4 7 7 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 The median is element 49 of the sorted 99 element array. The mean value for this run is: 681 / 99 = 6. .******** Mean ******** The mean is the average value of the data items.

******** Mode ******** Response 25 Outline Frequency Histogram 1 0 1 5 2 0 2 5 Program Output 5 1 1 * 2 3 *** 3 4 **** 4 5 ***** 5 8 ******** 6 9 ********* 7 23 *********************** 8 27 *************************** 9 19 ******************* The mode is the most frequent value. . Inc.  2000 Prentice Hall. For this run the mode is 8 which occurred 27 times. All rights reserved.

at most n steps. where 2^nn > # of elements  30 element array takes at most 5 steps ± 52 > 30  2000 Prentice Hall.8  Binary search ± Can only be used on sorted arrays ± Compares middle element with key  If equal. repeat search through the first half of the array  If key > middle. .26 Searching Arrays: Linear Search and Binary Search  Search array for a key value  Linear search ± Compare each element of array with key value ± Useful for small and unsorted arrays 4. match found  If key < middle. repeat search through the last half of the array ± Very fast. All rights reserved. Inc.

1 3  2000 Prentice Hall. 2 }. All rights reserved.tables with rows. Row 0 Row 1 Row 2 Column 0 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] Column 1 a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] Column 2 a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] Column 3 a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Column subscript Array name Row subscript  Initialize int b[ 2 ][ 2 ] = { { 1. columns ± Like matrices: specify row. { 3.27 4. then column. { 3. 1 3 2 4 ± Initializers grouped by row in braces int b[ 2 ][ 2 ] = { { 1 }. 4 } }. 4 } }. Inc.9 Multiple-Subscripted Arrays  Multiple subscripts . 0 4 .

causing a syntax error  2000 Prentice Hall.  Will try to call function b. ± Will output the value of 0 ± Cannot reference with commas cout << b( 0.9 Multiple-Subscripted Arrays  Referenced like normal cout << b[ 0 ][ 1 ]. All rights reserved.28 4. . 1 ). Inc.

using std::setiosflags. const int students = 3. #include <iomanip> using std::setw.2 Initialize studentgrades[][] 2. { 70. double average( int []. exams ). // number of students // number of exams 29 Outline 1. cout << "The array is:\n". const int exams = 4. Initialize variables 1. int ). int. using std::ios. void printArray( int [][ exams ].23: fig04_23. int ). 86.cpp // Double-subscripted array example #include <iostream> using std::cout. . and average Each row is a particular student.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 33 // Fig. students. int maximum( int [][ exams ]. int. 90. 81 } }. using std::setprecision. 4. using std::endl. int minimum( int [][ exams ]. 78 }. students ][ exams ] = 86. 68. exams ) << Hall. Inc. int ). int. 87. Call functions minimum. int ). int main() { int studentGrades[ { { 77. cout << "\n\nLowest grade: "  2000 Prentice minimum( studentGrades. printArray( studentGrades.1 Define functions to take double scripted arrays 1. students. All rights reserved. 89. each column is the grades on the exam. { 96. 73 }. maximum.