1 Arrays Outline Multidimensional Arrays Case Study Computing

  • Slides: 29
Download presentation
1 Arrays Outline Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays

1 Arrays Outline Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays 2003 Prentice Hall, Inc. All rights reserved.

2 Multidimensional Arrays • Multiple subscripts – – a[ i ][ j ] Tables

2 Multidimensional Arrays • Multiple subscripts – – a[ i ][ j ] Tables with rows and columns Specify row, then column “Array of arrays” • a[0] is an array of 4 elements • a[0][0] is the first element of that array Row 0 Column 0 a[ 0 ] Column 1 a[ 0 ][ 1 ] Column 2 a[ 0 ][ 2 ] Column 3 a[ 0 ][ 3 ] Row 1 a[ 1 ][ 0 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ] Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 3 ] Column subscript Array name Row subscript 2003 Prentice Hall, Inc. All rights reserved.

3 Multidimensional Arrays • To initialize – Default of 0 – Initializers grouped by

3 Multidimensional Arrays • To initialize – Default of 0 – Initializers grouped by row in braces int b[ 2 ] = { { 1, 2 }, { 3, 4 } }; Row 0 Row 1 int b[ 2 ] = { { 1 }, { 3, 4 } }; 1 2 3 4 1 0 3 4 Not enough initializers for the first row the rest elements of the row are by default 0 2003 Prentice Hall, Inc. All rights reserved.

4 Multidimensional Arrays • Referenced like normal cout << b[ 0 ][ 1 ];

4 Multidimensional Arrays • Referenced like normal cout << b[ 0 ][ 1 ]; – Outputs 0 – Cannot reference using commas 1 0 3 4 cout << b[ 0, 1 ]; • Syntax error • Function prototypes – Must specify sizes of subscripts • First subscript not necessary, as with single-scripted arrays – void print. Array( int [][ 3 ] ); 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 7. 22: fig 07_22. cpp // Initializing multidimensional arrays.

1 2 3 // Fig. 7. 22: fig 07_22. cpp // Initializing multidimensional arrays. #include <iostream> Outline Note the format of the prototype. 4 5 6 using std: : cout; using std: : endl; 7 8 void print. Array( int [][ 3 ] ); 9 10 11 12 13 14 int main() { int array 1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } }; int array 2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 }; int array 3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } }; Note the various initialization styles. The elements in array 2 are assigned to the first row and then the second. 15 16 17 cout << "Values in array 1 by row are: " << endl; print. Array( array 1 ); 18 19 20 cout << "Values in array 2 by row are: " << endl; print. Array( array 2 ); 21 22 23 cout << "Values in array 3 by row are: " << endl; print. Array( array 3 ); 24 25 return 0; 26 27 // indicates successful termination } // end main 2003 Prentice Hall, Inc. All rights reserved. 5

28 29 30 31 32 33 34 35 36 37 38 39 40 41

28 29 30 31 32 33 34 35 36 37 38 39 40 41 For loops are often used to // function to output array with two rows and three columns iterate through arrays. Nested void print. Array( int a[][ 3 ] ) loops are helpful with { multiple-subscripted arrays. for ( int i = 0; i < 2; i++ ) { // for each row for ( int j = 0; j < 3; j++ ) cout << a[ i ][ j ] << ' '; cout << endl; Outline // output column values // start new line of output } // end outer for structure } // end function print. Array Values in array 1 by row are: 123 456 Values in array 2 by row are: 123 450 Values in array 3 by row are: 120 400 2003 Prentice Hall, Inc. All rights reserved. 6

7 Multidimensional Arrays • Next: program showing initialization – – After, program to keep

7 Multidimensional Arrays • Next: program showing initialization – – After, program to keep track of students grades Multiple-subscripted array (table) Rows are students Columns are grades Quiz 1 Quiz 2 2003 Prentice Hall, Inc. All rights reserved. Student 0 95 85 Student 1 80 89

1 2 3 // Double-subscripted array example. #include <iostream> 4 5 6 7 8

1 2 3 // Double-subscripted array example. #include <iostream> 4 5 6 7 8 using 9 10 #include <iomanip> 11 12 13 using std: : setw; using std: : setprecision; 14 15 16 const int students = 3; const int exams = 4; 17 18 19 20 21 22 // function prototypes int minimum( int [][ exams ], int ); int maximum( int [][ exams ], int ); double average( int [], int ); void print. Array( int [][ exams ], int ); Outline std: : cout; std: : endl; std: : fixed; std: : left; // number of students // number of exams 23 2003 Prentice Hall, Inc. All rights reserved. 8

24 25 26 27 28 29 30 int main() { // initialize student grades

24 25 26 27 28 29 30 int main() { // initialize student grades for three students (rows) int student. Grades[ students ][ exams ] = { { 77, 68, 86, 73 }, { 96, 87, 89, 78 }, { 70, 90, 86, 81 } }; Outline 31 32 33 34 // output array student. Grades cout << "The array is: n"; print. Array( student. Grades, students, exams ); 35 36 37 38 39 40 // determine smallest and largest grade values cout << "nn. Lowest grade: " << minimum( student. Grades, students, exams ) << "n. Highest grade: " NOTICE: Determines this element the is average << maximum( student. Grades, students, exams ) << 'n'; 41 42 cout << fixed << setprecision( 2 ); 43 44 45 46 47 48 49 // calculate average grade for each student for ( int person = 0; person < students; person++ cout << "The average grade for student " << person << " is " << average( student. Grades[ person ], exams ) << endl; 50 51 return 0; 52 53 } // end main for passed by onereference student. We sincepass it isthe an array/row by itself. containing the student’s grades. Note that student. Grades[0] is ) itself an array. // indicates successful termination 2003 Prentice Hall, Inc. All rights reserved. 9

54 55 56 57 58 59 60 61 62 63 64 65 66 67

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 // find minimum grade int minimum( int grades[][ exams ], int pupils, int tests ) { int low. Grade = 100; // initialize to highest possible grade Outline for ( int i = 0; i < pupils; i++ ) for ( int j = 0; j < tests; j++ ) if ( grades[ i ][ j ] < low. Grade ) low. Grade = grades[ i ][ j ]; return low. Grade; } // end function minimum 2003 Prentice Hall, Inc. All rights reserved. 10

70 71 72 73 74 75 76 77 78 79 80 81 82 83

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 // find maximum grade int maximum( int grades[][ exams ], int pupils, int tests ) { int high. Grade = 0; // initialize to lowest possible grade Outline for ( int i = 0; i < pupils; i++ ) for ( int j = 0; j < tests; j++ ) if ( grades[ i ][ j ] > high. Grade ) high. Grade = grades[ i ][ j ]; return high. Grade; } // end function maximum 86 2003 Prentice Hall, Inc. All rights reserved. 11

87 88 89 90 91 92 93 94 95 96 97 98 // determine

87 88 89 90 91 92 93 94 95 96 97 98 // determine average grade for particular student double average( int set. Of. Grades[], int tests ) { int total = 0; Outline // total all grades for one student for ( int i = 0; i < tests; i++ ) total += set. Of. Grades[ i ]; return static_cast< double >( total ) / tests; // average } // end function maximum 2003 Prentice Hall, Inc. All rights reserved. 12

99 100 // Print the array 101 void print. Array( int grades[][ exams ],

99 100 // Print the array 101 void print. Array( int grades[][ exams ], int pupils, int tests ) 102 { 103 // set left justification and output column heads 104 cout << left << " [0] [1] [2] [3]" ; 105 106 107 // output grades in tabular format for ( int i = 0; i < pupils; i++ ) { 108 109 110 // output label for row cout << "nstudent. Grades[" << i << "] "; 111 112 113 114 // output one grades for one student for ( int j = 0; j < tests; j++ ) cout << setw( 5 ) << grades[ i ][ j ]; 115 116 Outline } // end outer for 117 118 } // end function print. Array 2003 Prentice Hall, Inc. All rights reserved. 13

The array is: [0] student. Grades[0] 77 student. Grades[1] 96 student. Grades[2] 70 [1]

The array is: [0] student. Grades[0] 77 student. Grades[1] 96 student. Grades[2] 70 [1] 68 87 90 [2] 86 89 86 [3] 73 78 81 Outline 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 2003 Prentice Hall, Inc. All rights reserved. 14

#include <iostream> using std: : cout; std: : endl; std: : fixed; std: :

#include <iostream> using std: : cout; std: : endl; std: : fixed; std: : left; Passing Arrays in Functions #include <iomanip> using std: : setw; using std: : setprecision; void modify( int [][ 4 ]); void modify. Row(int []); const int row = 3; const int column = 4; int main() { int a[ row][ column ] = { { 77, 68, 86, 73 }, { 96, 87, 89, 78 }, { 70, 90, 86, 81 } }; for (int i=0; i<row; i++) { for (int j=0; j<column; j++) cout <<a[ i ][ j ]<<" "; cout<<endl; } 2003 Prentice Hall, Inc. All rights reserved. 15

modify(a); cout<<endl; Passing Arrays in Functions for ( i=0; i<row; i++) { for (int

modify(a); cout<<endl; Passing Arrays in Functions for ( i=0; i<row; i++) { for (int j=0; j<column; j++) cout <<a[ i ][ j ]<<" "; cout<<endl; } cout<<endl; modify. Row(a[1]); for ( i=0; i<column; i++) { cout <<a[ 1][ i ]<<" "; } cout<<endl; for ( i = 0; i < row; i++ ) { // output label for row cout << "nstudent. Grades[" << i << "] "; for (int j = 0; j < column; j++ ) cout << setw( 5 ) << a[ i ][ j ]; } // end outer for cout<<endl; return 0; // indicates successful termination } // end main 2003 Prentice Hall, Inc. All rights reserved. 16

Passing Arrays in Functions void modify( int a[][ 4 ]) { for (int i=0;

Passing Arrays in Functions void modify( int a[][ 4 ]) { for (int i=0; i<row; i++) { for (int j=0; j<column; j++) a[ i ][ j ] = a[ i ][ j ] + 1; cout<<endl; } for ( i=0; i<row; i++) { for ( int j=0; j<column; j++) cout <<a[ i ][ j ]<<" "; cout<<endl; } } void modify. Row( int a[]) { for ( int i=0; i<column; i++) { a[ i ] = a[ i ] + 1; cout<<endl; } for ( i=0; i<column; i++) { cout <<a[ i ]<<" "; } cout<<endl; } 2003 Prentice Hall, Inc. All rights reserved. 17

Case Study: Computing Mean, Median and Mode Using Arrays • Mean – Average (sum/number

Case Study: Computing Mean, Median and Mode Using Arrays • Mean – Average (sum/number of elements) • Median – Number in middle of sorted list – 1, 2, 3, 4, 5 (3 is median) – If even number of elements, take average of middle two • Mode – Number that occurs most often – 1, 1, 1, 2, 3, 3, 4, 5 (1 is mode) 2003 Prentice Hall, Inc. All rights reserved. 18

1 2 3 4 // *********** // This program introduces the topic of survey

1 2 3 4 // *********** // This program introduces the topic of survey data analysis. // It computes the mean, median, and mode of the data. #include <iostream> 5 6 7 8 9 using 10 11 #include <iomanip> 12 13 14 using std: : setw; using std: : setprecision; 15 16 17 18 19 20 void void 21 22 23 24 int main() { const int response. Size = 99; Outline std: : cout; std: : endl; std: : fixed; std: : showpoint; mean( const int [], int ); median( int [], int ); mode( int [], int ); bubble. Sort( int[], int ); print. Array( const int[], int ); // size of array responses 25 2003 Prentice Hall, Inc. All rights reserved. 19

26 int frequency[ 10 ] = { 0 }; 27 28 29 30 31

26 int frequency[ 10 ] = { 0 }; 27 28 29 30 31 32 33 34 35 36 37 38 39 // initialize array responses int response[ response. Size ] = { 6, 7, 8, 9, 8, 7, 8, 9, 5, 9, 8, 7, 8, 6, 7, 8, 9, 3, 9, 8, 7, 7, 8, 9, 7, 6, 7, 8, 7, 9, 8, 7, 8, 9, 7, 5, 6, 7, 2, 5, 3, 9, 4, 7, 8, 9, 6, 8, 7, 8, 9, 7, 4, 4, 2, 5, 3, 8, 7, 4, 5, 6, 1, 6, 5, 7, 8, 40 41 42 43 44 // process responses mean( response, response. Size ); median( response, response. Size ); mode( frequency, response. Size ); 45 46 return 0; 47 48 // initialize array frequency Outline 8, 9, 7, 8, 8, 7, 8, 9, 9, 2, 5, 3, 6, 4, 7, 8, 5, 6, 7 }; // indicates successful termination } // end main 49 2003 Prentice Hall, Inc. All rights reserved. 20

50 51 52 53 // calculate average of all response values void mean( const

50 51 52 53 // calculate average of all response values void mean( const int answer[], int array. Size ) { int total = 0; 54 55 cout << "****n 56 57 58 59 // total response values for ( int i = 0; i < array. Size; i++ ) total += answer[ i ]; 60 61 62 // format and output results cout << fixed << setprecision( 4 ); 63 64 65 66 67 68 69 70 71 cout << << 72 73 Outline Meann****n" ; "The mean is the average value of the datan" "items. The mean is equal to the total ofn" "all the data items divided by the numbern" We cast to a double to get "of data items (" << array. Size "). The mean value fornthis run is: " decimal points for the average (instead of an integer). total << " / " << array. Size << " = " static_cast< double >( total ) / array. Size "nn"; } // end function mean 74 2003 Prentice Hall, Inc. All rights reserved. 21

75 76 77 78 79 // sort array and determine median element's value void

75 76 77 78 79 // sort array and determine median element's value void median( int answer[], int size ) { cout << "n****n Mediann****n" << "The unsorted array of responses is" ; Sort array by passing it to a function. This keeps the output unsorted array program modular. 80 81 print. Array( answer, size ); // 82 83 bubble. Sort( answer, size ); // sort array 84 85 86 87 88 89 90 91 92 93 94 Outline cout << "nn. The sorted array is"; print. Array( answer, size ); // output sorted array // display median element cout << "nn. The median is element " << size / 2 << " ofnthe sorted " << size << " element array. n. For this run the median is " << answer[ size / 2 ] << "nn"; } // end function median 95 2003 Prentice Hall, Inc. All rights reserved. 22

96 // determine most frequent response 97 void mode( int freq[], int answer[], int

96 // determine most frequent response 97 void mode( int freq[], int answer[], int size ) 98 { 99 int largest = 0; // represents largest frequency 100 int mode. Value = 0; // represents most frequent response 101 102 cout << "n****n 103 104 105 106 // initialize frequencies to 0 for ( int i = 1; i <= 9; i++ ) freq[ i ] = 0; 107 108 109 110 // summarize frequencies for ( int j = 0; j < size; j++ ) ++freq[ answer[ j ] ]; 111 112 113 114 // output headers for result columns cout << "Response" << setw( 11 ) << "Frequency" << setw( 19 ) << "Histogramn"; Outline Moden****n" ; Fill the frequency array… 115 116 117 2003 Prentice Hall, Inc. All rights reserved. 23

118 119 120 121 122 123 124 125 126 127 128 // output results

118 119 120 121 122 123 124 125 126 127 128 // output results for ( int rating = 1; rating <= 9; rating++ ) { cout << setw( 8 ) << rating << setw( 11 ) The mode is the << freq[ rating ] << " "; Outline value that occurs most often (has the highest value in freq). largest frequency value // keep track of mode value and if ( freq[ rating ] > largest ) { largest = freq[ rating ]; mode. Value = rating; } // end if 129 130 131 132 // output histogram bar representing frequency value for ( int k = 1; k <= freq[ rating ]; k++ ) cout << '*'; 133 134 cout << 'n'; // begin new line of output 135 136 } // end outer for 137 138 139 140 141 // display the mode value cout << "The mode is the most frequent value. n" << "For this run the mode is " << mode. Value << " which occurred " << largest << " times. " << endl; 142 143 } // end function mode 2003 Prentice Hall, Inc. All rights reserved. 24

144 145 // function that sorts an array with bubble sort algorithm 146 void

144 145 // function that sorts an array with bubble sort algorithm 146 void bubble. Sort( int a[], int size ) 147 { 148 int hold; // temporary location used to swap elements 149 150 151 152 153 154 Outline // loop to control number of passes for ( int i = 0; i < size; i++ ) // loop to control number of comparisons per pass for ( int j = i+1; j < size; j++ ) 155 156 157 158 159 160 // swap elements if out of order if ( a[ j ] < a[ i] ) { hold = a[ j ]; a[ j ] = a[ i]; a[ i] = hold; 161 162 } // end if 163 164 } // end function bubble. Sort 165 2003 Prentice Hall, Inc. All rights reserved. 25

166 // output array contents (20 values per row) 167 void print. Array( const

166 // output array contents (20 values per row) 167 void print. Array( const int a[], int size ) 168 { 169 for ( int i = 0; i < size; i++ ) { 170 171 172 if ( i % 20 == 0 ) cout << endl; 173 174 cout << setw( 2 ) << a[ i ]; 175 176 Outline // begin new line every 20 values } // end for 177 178 } // end function print. Array 2003 Prentice Hall, Inc. All rights reserved. 26

**** Mean **** The mean is the average value of the data items. The

**** Mean **** The mean is the average value of the data items. The mean is equal to the total of all the data items divided by the number of data items (99). The mean value for this run is: 681 / 99 = 6. 8788 **** Median **** The unsorted array of responses is 6 7 8 9 8 9 7 8 9 5 9 8 7 8 6 7 8 9 3 9 8 7 7 8 9 8 9 7 8 9 6 7 8 7 9 8 9 2 7 8 9 8 9 7 5 3 5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8 7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7 The sorted 1 2 2 2 3 5 6 6 7 7 7 8 8 8 9 9 9 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 5 7 8 8 9 5 7 8 8 9 Outline 5 7 8 8 The median is element 49 of the sorted 99 element array. For this run the median is 7 2003 Prentice Hall, Inc. All rights reserved. 27

**** Mode **** Response Frequency Histogram 1 1 * 2 3 *** 3 4

**** Mode **** Response Frequency Histogram 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. For this run the mode is 8 which occurred 27 times. Outline 2003 Prentice Hall, Inc. All rights reserved. 28

// count the number of zeros in the upper diagonal of a matrix #include

// count the number of zeros in the upper diagonal of a matrix #include <iostream> using std: : cout; using std: : endl; const int row = 3; const int column = 4; int main() { int counter = 0; int a[ row][ column ] = { { 0, 1, 0, 4}, { -1, 2, 0, 7}, { 3, 2, 8, 0} }; for (int i = 0; i < row; i++) { for (int j = i+1; j < column; j++) { if (a[ i ][ j ] == 0) ++counter; } } cout <<"The number of zeros in te upper diagonalnof the matrix is: “ <<counter<<endl; return 0 } 2003 Prentice Hall, Inc. All rights reserved. 29