Arrays as Lists with examples 1 Review Arrays

  • Slides: 89
Download presentation
Arrays as Lists with examples 1

Arrays as Lists with examples 1

Review • Arrays – Structures of related data items of the same type –

Review • Arrays – Structures of related data items of the same type – Data items (called array elements) are stored at consecutive memory locations – Static entity (same size throughout program) • Textbook mentions two types – Pointer-based arrays (built into C++) – Arrays as objects (we’ll see later in the course) 2

Arrays • To refer to an element – Specify array name and position number

Arrays • To refer to an element – Specify array name and position number (index) – Format: arrayname[ position number ] – First element at position 0 • Example: N-element array c c[ 0 ], c[ 1 ] … c[ n - 1 ] – Nth element is at position N-1 3

Arrays • Array elements like other variables – Assignment, printing for an integer array

Arrays • Array elements like other variables – Assignment, printing for an integer array c c[0] = 3; cout << c[0]; • Can perform operations inside subscript c[5 – 2] same as c[3] 4

Arrays Name of array (Note that all elements of this array have the same

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

Declaring Arrays • When declaring arrays, specify – Name – Type of array •

Declaring Arrays • When declaring arrays, specify – Name – Type of array • Any data type – Number of elements – type array. Name[ array. Size ]; int c[ 10 ]; // array of 10 integers float d[ 3284 ]; // array of 3284 floats int b[ 100 ], x[ 27 ]; // Declaring multiple arrays 6

Examples Using Arrays • • • Initializing arrays Using arrays Character strings Static arrays

Examples Using Arrays • • • Initializing arrays Using arrays Character strings Static arrays Passing arrays to functions 7

How to use setw() – Set Field Width #include <iomanip> setw ( int n

How to use setw() – Set Field Width #include <iomanip> setw ( int n ); • Sets a value to be used as the field width for the next insertion operation. • The field width determines the minimum number of characters to be written. • If the standard width of the representation is shorter than the field width, the representation is padded with fill characters (setfill). 8

How to use setw() – Set Field Width • n = Number of characters

How to use setw() – Set Field Width • n = Number of characters to be used as field width. #include <iostream> #include <iomanip> int main () { cout << setw (10); cout << 77 << endl; return 0; } This code uses setw to set the field width to 10 characters. 9

Examples Using Arrays • Initializing arrays – For loop • Set each element –

Examples Using Arrays • Initializing arrays – For loop • Set each element – Initializer list • Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 }; • If not enough initializers, rightmost elements 0 • If too many syntax error – To set every element to same value int n[ 5 ] = { 0 }; – If array size omitted, initializers determine size int n[] = { 1, 2, 3, 4, 5 }; • 5 initializers, therefore 5 element array 10

1 2 3 // Initializing an array. #include <iostream> 4 5 6 using std:

1 2 3 // Initializing an array. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 14 int main() { int n[ 10 ]; // n is an array of 10 integers 15 16 17 18 for ( int i = 0; i < 10; i++ ) n[ i ] = 0; // set element at location i to 0 Declare a 10 -element array of integers. Initialize array to 0 using a for loop. Note that the array has // initialize elements of array n to 0 elements n[0] to n[9]. 19 20 cout << "Element" << setw( 13 ) << "Value" << endl; 21 22 23 24 // output contents of array n in tabular format for ( int j = 0; j < 10; j++ ) cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl; 25 11

26 return 0; // indicates successful termination 27 28 } // end main Element

26 return 0; // indicates successful termination 27 28 } // end main Element 0 1 2 3 4 5 6 7 8 9 Value 0 0 0 0 0 12

1 2 3 // Initializing an array with a declaration. #include <iostream> 4 5

1 2 3 // Initializing an array with a declaration. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 14 15 16 17 int main() list. { // use initializer list to initialize array n int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; cout << "Element" << setw( 13 ) << "Value" << endl; 18 19 20 21 // output contents of array n in tabular format for ( int i = 0; i < 10; i++ ) cout << setw( 7 ) << i << setw( 13 ) << n[ i ] << endl; 22 23 return 0; // indicates successful termination 24 25 } // end main Note the use of the initializer 13

Element Value 0 32 1 27 2 64 3 18 4 95 5 14

Element Value 0 32 1 27 2 64 3 18 4 95 5 14 6 90 7 70 8 60 9 37 14

Examples Using Arrays • Array size – Can be specified with constant variable /

Examples Using Arrays • Array size – Can be specified with constant variable / named constant const int size = 20; – Named constants cannot be changed – Named constants must be initialized when declared 15

1 2 3 // Initialize array s to the even integers from 2 to

1 2 3 // Initialize array s to the even integers from 2 to 20. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 14 15 16 17 int main() { // constant variable can be used to specify array size const int array. Size = 10; int s[ array. Size ]; // array s has 10 elements 18 19 20 for ( int i = 0; i < array. Size; i++ ) // set the values s[ i ] = 2 + 2 * i; 21 22 cout << "Element" << setw( 13 ) << "Value" << endl; 23 Note use of const keyword. Only constants can specify array sizes. The program becomes more scalable when we set the array size using a const variable. We can change array. Size, and all the loops will still work (otherwise, we’d have to update every loop in the program). 16

24 25 26 // output contents of array s in tabular format for (

24 25 26 // output contents of array s in tabular format for ( int j = 0; j < array. Size; j++ ) cout << setw( 7 ) << j << setw( 13 ) << s[ j ] << endl; 27 28 return 0; // indicates successful termination 29 30 } // end main Element 0 1 2 3 4 5 6 7 8 9 Value 2 4 6 8 10 12 14 16 18 20 17

1 2 // A const object must be initialized. 3 4 5 6 int

1 2 // A const object must be initialized. 3 4 5 6 int main() { const int x; // Error: x must be initialized 7 8 x = 7; // Error: cannot modify a const variable 9 10 return 0; // indicates successful termination 11 12 } // end main Uninitialized const results in a syntax error. Attempting to modify the const is another error. 18

1 2 3 // Compute the sum of the elements of the array. #include

1 2 3 // Compute the sum of the elements of the array. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 int main() { const int array. Size = 10; 11 12 int a[ array. Size ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 13 14 int total = 0; 15 16 17 18 19 20 // sum contents of array a for ( int i = 0; i < array. Size; i++ ) total += a[ i ]; cout << "Total of array element values is " << total << endl; 21 22 return 0; // indicates successful termination 23 24 } // end main Total of array element values is 55 19

1 2 3 // Histogram printing program. #include <iostream> 4 5 6 using std:

1 2 3 // Histogram printing program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 14 15 int main() { const int array. Size = 10; int n[ array. Size ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 16 17 18 cout << "Element" << setw( 13 ) << "Value" << setw( 17 ) << "Histogram" << endl; 19 20 21 22 23 // for each element of array n, output a bar in histogram for ( int i = 0; i < array. Size; i++ ) { Prints asterisks corresponding cout << setw( 7 ) << i << setw( 13 ) to size of array element, << n[ i ] << setw( 9 ); 24 25 26 for ( int j = 0; j < n[ i ]; j++ ) // print one bar cout << '*'; n[i]. 20

27 28 cout << endl; // start next line of output 29 30 }

27 28 cout << endl; // start next line of output 29 30 } // end outer for structure 31 32 return 0; // indicates successful termination 33 34 } // end main Element 0 1 2 3 4 5 6 7 8 9 Value Histogram 19 ********** 3 *** 15 ******** 7 ******* 11 ****** 9 ***** 13 ******* 5 ***** 17 ********* 1 * 21

1 2 3 // Roll a six-sided die 6000 times. #include <iostream> 4 5

1 2 3 // Roll a six-sided die 6000 times. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 #include <cstdlib> #include <ctime> 14 15 16 17 18 int main() { const int array. Size = 7; int frequency[ array. Size ] = { 0 }; 19 20 srand( time( 0 ) ); // random-number generator 21 22 23 24 25 // roll die 6000 times for ( int roll = 1; roll <= 6000; roll++ ) ++frequency[ 1 + rand() % 6 ]; // replaces 20 -line switch An array is used instead of 6 regular variables, and the proper element can be updated easily (without needing a switch). This creates a number between 1 and 6, which determines the index of frequency[] that should be incremented. 22

26 27 cout << "Face" << setw( 13 ) << "Frequency" << endl; 28

26 27 cout << "Face" << setw( 13 ) << "Frequency" << endl; 28 29 30 31 32 // output frequency elements 1 -6 in tabular format for ( int face = 1; face < array. Size; face++ ) cout << setw( 4 ) << face << setw( 13 ) << frequency[ face ] << endl; 33 34 return 0; // indicates successful termination 35 36 } // end main Face 1 2 3 4 5 6 Frequency 1003 1004 999 980 1013 1001 23

24 25 26 // loop 6000 times and summarize results for ( int roll

24 25 26 // loop 6000 times and summarize results for ( int roll = 1; roll <= 6000; roll++ ) { face = 1 + rand() % 6; // random number from 1 to 6 27 28 29 // determine face value and increment appropriate counter switch ( face ) { 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 case 1: // rolled 1 ++frequency 1; break; case 2: // rolled 2 ++frequency 2; break; case 3: // rolled 3 ++frequency 3; break; case 4: // rolled 4 ++frequency 4; break; case 5: // rolled 5 ++frequency 5; break; 24

1 2 3 // Student poll program. #include <iostream> 4 5 6 using std:

1 2 3 // Student poll program. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 14 15 16 int main() { // define array sizes const int response. Size = 40; // size of array responses const int frequency. Size = 11; // size of array frequency 17 18 19 20 21 // place survey responses in array responses int responses[ response. Size ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 }; 22 23 24 // initialize frequency counters to 0 int frequency[ frequency. Size ] = { 0 }; 25 25

26 27 28 29 30 // for each answer, select value of an element

26 27 28 29 30 // for each answer, select value of an element of array // responses and use that value as subscript in array // frequency to determine element to increment for ( int answer = 0; answer < response. Size; answer++ ) ++frequency[ responses[answer] ]; 31 32 33 // display results cout << "Rating" << setw( 17 ) << "Frequency" << endl; 34 35 36 37 38 // output frequencies in tabular format for ( int rating = 1; rating < frequency. Size; rating++ ) cout << setw( 6 ) << rating << setw( 17 ) << frequency[ rating ] << endl; 39 40 return 0; // indicates successful termination 41 42 } // end main responses[answer] is the rating (from 1 to 10). This determines the index in frequency[] to increment. 26

Rating Frequency 1 2 2 2 3 2 4 2 5 5 6 11

Rating Frequency 1 2 2 2 3 2 4 2 5 5 6 11 7 5 8 7 9 1 10 3 27

Examples Using Arrays • Strings – Arrays of characters – All strings end with

Examples Using Arrays • Strings – Arrays of characters – All strings end with the null character ('') – Examples char string 1[] = "hello"; // “hello” is a string literal • Null character implicitly added • string 1 has 6 elements • Equivalent statement: char string 1[] = {'h', 'e', 'l', 'o', '’}; – Subscripting is the same String 1[ 0 ] is 'h' string 1[ 2 ] is 'l' 28

Examples Using Arrays • Input from keyboard char string 2[ 10 ]; cin >>

Examples Using Arrays • Input from keyboard char string 2[ 10 ]; cin >> string 2; – Puts user input in string • Stops at first white space character • Adds null character – If too much text entered, data written beyond array • We want to avoid this by using setw(…) or getline(…) • Printing strings – cout << string 2 << endl; • Does not work for other array types – Characters printed until null found 29

1 2 3 // Treating character arrays as strings. #include <iostream> 4 5 6

1 2 3 // Treating character arrays as strings. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 10 11 12 int main() { char string 1[ 20 ], // reserves 20 characters char string 2[] = "string literal"; // reserves 15 characters 13 14 15 16 // read string from user into array string 2 cout << "Enter the string "hello there": " ; cin >> string 1; // reads "hello" [space terminates input] 17 18 19 20 // output strings cout << "string 1 is: " << string 1 << "nstring 2 is: " << string 2; 21 22 cout << "nstring 1 with spaces between characters is: n" ; Two different ways to declare strings. string 2 is initialized, and its size determined automatically. Examples of reading strings from the keyboard and printing them out. 23 30

24 25 26 // output characters until null character is reached for ( int

24 25 26 // output characters until null character is reached for ( int i = 0; string 1[ i ] != ''; i++ ) cout << string 1[ i ] << ' '; 27 28 29 cin >> string 1; // reads "there" cout << "nstring 1 is: " << string 1 << endl; 30 31 return 0; // indicates successful termination 32 33 } // end main Can access the characters in a string using array notation. The loop ends when the null character is found. Enter the string "hello there": hello there string 1 is: hello string 2 is: string literal string 1 with spaces between characters is: hello string 1 is: there 31

Examples Using Arrays • Recall static storage – If static, local variables save values

Examples Using Arrays • Recall static storage – If static, local variables save values between function calls – Visible only in function body – Can declare local arrays to be static • Initialized to zero static int array[3]; • If not static – Created (and destroyed) in every function call 32

1 2 3 // Static arrays are initialized to zero. #include <iostream> 4 5

1 2 3 // Static arrays are initialized to zero. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 void static. Array. Init( void ); // function prototype void automatic. Array. Init( void ); // function prototype 10 11 12 13 14 15 int main() { cout << "First call to each function: n" ; static. Array. Init(); automatic. Array. Init(); 16 17 18 19 20 cout << "nn. Second call to each function: n" ; static. Array. Init(); automatic. Array. Init(); cout << endl; 21 22 return 0; // indicates successful termination 23 24 } // end main 25 33

26 27 28 29 30 // function to demonstrate a static local array Static

26 27 28 29 30 // function to demonstrate a static local array Static array, initialized void static. Array. Init( void ) on first function call. { // initializes elements to 0 first time function is called static int array 1[ 3 ]; 31 32 cout << "n. Values on entering static. Array. Init: n" ; 33 34 35 36 // output contents of array 1 for ( int i = 0; i < 3; i++ ) cout << "array 1[" << i << "] = " << array 1[ i ] << " "; 37 38 cout << "n. Values on exiting static. Array. Init: n" ; 39 40 41 42 43 // modify and output contents of array 1 for ( int j = 0; j < 3; j++ ) cout << "array 1[" << j << "] = " << ( array 1[ j ] += 5 ) << " "; 44 45 } // end function static. Array. Init to zero Array data is changed; the modified values stay. 46 34

47 48 49 50 51 // function to demonstrate an automatic local array void

47 48 49 50 51 // function to demonstrate an automatic local array void automatic. Array. Init( void ) { // initializes elements each time function is called int array 2[ 3 ] = { 1, 2, 3 }; 52 53 cout << "nn. Values on entering automatic. Array. Init: n" ; 54 55 56 57 // output contents of array 2 for ( int i = 0; i < 3; i++ ) cout << "array 2[" << i << "] = " << array 2[ i ] << " "; 58 59 cout << "n. Values on exiting automatic. Array. Init: n" ; 60 61 62 63 64 // modify and output contents of array 2 for ( int j = 0; j < 3; j++ ) cout << "array 2[" << j << "] = " << ( array 2[ j ] += 5 ) << " "; 65 66 } // end function automatic. Array. Init Automatic array, recreated with every function call. Although the array is changed, it will be destroyed when the function exits and the changes will be lost. 35

First call to each function: Values on entering static. Array. Init: array 1[0] =

First call to each function: Values on entering static. Array. Init: array 1[0] = 0 array 1[1] = 0 array 1[2] = 0 Values on exiting static. Array. Init: array 1[0] = 5 array 1[1] = 5 array 1[2] = 5 Values on entering automatic. Array. Init: array 2[0] = 1 array 2[1] = 2 array 2[2] = 3 Values on exiting automatic. Array. Init: array 2[0] = 6 array 2[1] = 7 array 2[2] = 8 Second call to each function: Values on entering static. Array. Init: array 1[0] = 5 array 1[1] = 5 array 1[2] = 5 Values on exiting static. Array. Init: array 1[0] = 10 array 1[1] = 10 array 1[2] = 10 Values on entering automatic. Array. Init: array 2[0] = 1 array 2[1] = 2 array 2[2] = 3 Values on exiting automatic. Array. Init: array 2[0] = 6 array 2[1] = 7 array 2[2] = 8 36

Passing Arrays to Functions • Specify name without brackets – To pass array my.

Passing Arrays to Functions • Specify name without brackets – To pass array my. Array to my. Function int my. Array[ 24 ]; my. Function( my. Array, 24 ); – Array size usually passed, but not required • Useful to iterate over all elements 37

Passing Arrays to Functions • Arrays are passed by-reference – Value of name of

Passing Arrays to Functions • Arrays are passed by-reference – Value of name of array is address of first element • Function knows where the array is stored • Can change original memory locations • Individual array elements are passed by-value – Like regular variables – square( my. Array[3] ); 38

Passing Arrays to Functions • Functions taking arrays – Function prototypes • void modify.

Passing Arrays to Functions • Functions taking arrays – Function prototypes • void modify. Array( int b[], int array. Size ); • void modify. Array( int [], int ); – Names optional in prototype • Both take an integer array and a single integer – No need for array size between brackets • Ignored by compiler – If declare array parameter as const • Cannot be modified • void do. Not. Modify( const int [] ); 39

1 2 3 // Passing arrays and individual array elements to functions. #include <iostream>

1 2 3 // Passing arrays and individual array elements to functions. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 void modify. Array( int [], int ); // appears strange void modify. Element( int ); 14 15 16 17 18 int main() { const int array. Size = 5; // size of array a int a[ array. Size ] = { 0, 1, 2, 3, 4 }; // initialize a 19 20 21 cout << "Effects of passing entire array by reference: " << "nn The values of the original array are: n" ; 22 23 24 25 // output original array for ( int i = 0; i < array. Size; i++ ) cout << setw( 3 ) << a[ i ]; Syntax for accepting an array in parameter list. 40

Pass array name (a) and size to function. Arrays are passed -by-reference. 26 27

Pass array name (a) and size to function. Arrays are passed -by-reference. 26 27 cout << endl; 28 29 30 31 32 // pass array a to modify. Array by reference modify. Array( a, array. Size ); cout << "The values of the modified array are: n" ; 33 34 35 36 // output modified array for ( int j = 0; j < array. Size; j++ ) cout << setw( 3 ) << a[ j ]; 37 38 39 40 41 // output value of a[ 3 ] cout << "nnn" << "Effects of passing array element by value: " << "nn The value of a[3] is " << a[ 3 ] << 'n'; 42 43 44 // pass array element a[ 3 ] by value modify. Element( a[ 3 ] ); 45 46 47 // output value of a[ 3 ] cout << "The value of a[3] is " << a[ 3 ] << endl; 48 49 return 0; // indicates successful termination 50 51 } // end main Pass a single array element by value; the original cannot be modified. 41

52 53 54 55 56 57 58 59 60 61 // in function modify.

52 53 54 55 56 57 58 59 60 61 // in function modify. Array, "b" points to // the original array "a" in memory void modify. Array( int b[], int size. Of. Array ) { // multiply each array element by 2 for ( int k = 0; k < size. Of. Array; k++ ) b[ k ] *= 2; } // end function modify. Array 62 63 64 65 66 67 68 69 70 71 // in function modify. Element, "e" is a local copy of // array element a[ 3 ] passed from main void modify. Element( int e ) { // multiply parameter by 2 cout << "Value in modify. Element is " << ( e *= 2 ) << endl; } // end function modify. Element Although named b, the array points to the original array a. It can modify a’s data. Individual array elements are passed by value, and the originals cannot be changed. 42

Effects of passing entire array by reference: The values of the original array are:

Effects of passing entire array by reference: The values of the original array are: 0 1 2 3 4 The values of the modified array are: 0 2 4 6 8 Effects of passing array element by value: The value of a[3] is 6 Value in modify. Element is 12 The value of a[3] is 6 43

1 2 3 // Demonstrating the const type qualifier. #include <iostream> 4 5 6

1 2 3 // Demonstrating the const type qualifier. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 void try. To. Modify. Array( const int [] ); 9 10 11 12 int main() { int a[] = { 10, 20, 30 }; 13 14 try. To. Modify. Array( a ); 15 16 cout << a[ 0 ] << ' ' << a[ 1 ] << ' ' << a[ 2 ] << 'n'; 17 18 return 0; // indicates successful termination 19 20 } // end main Array parameter declared as const. Array cannot be modified, even though it is passed by reference. 21 44

22 23 24 25 26 27 28 29 30 // In function try. To.

22 23 24 25 26 27 28 29 30 // In function try. To. Modify. Array, "b" cannot be used // to modify the original array "a" in main. void try. To. Modify. Array( const int b[] ) { b[ 0 ] /= 2; // error b[ 1 ] /= 2; // error b[ 2 ] /= 2; // error } // end function try. To. Modify. Array 45

Sorting Arrays • Sorting data – Important computing application – Virtually every organization must

Sorting Arrays • Sorting data – 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), no change • If decreasing order, elements exchanged – Repeat these steps for every element 46

Sorting Arrays • Example: – Go left to right, and exchange elements as necessary

Sorting Arrays • Example: – Go left to right, and exchange elements as necessary • One pass for each element – – – – Original: 3 4 2 7 6 Pass 1: 3 2 4 6 7 (elements exchanged) Pass 2: 2 3 4 6 7 Pass 3: 2 3 4 6 7 (no changes needed) Pass 4: 2 3 4 6 7 Pass 5: 2 3 4 6 7 Small elements "bubble" to the top (like 2 in this example) 47

Sorting Arrays • Swapping variables int x = 3, y = 4; y =

Sorting Arrays • Swapping variables int x = 3, y = 4; y = x; x = y; • What happened? – Both x and y are 3! – Need a temporary variable • Solution int x = 3, y = 4, temp = 0; temp = x; // temp gets 3 x = y; // x gets 4 y = temp; // y gets 3 48

1 2 3 // This program sorts an array's values into ascending order. #include

1 2 3 // This program sorts an array's values into ascending order. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 using std: : setw; 11 12 13 14 15 16 int main() { const int array. Size = 10; // size of array a int a[ array. Size ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; int hold; // temporary location used to swap array elements 17 18 cout << "Data items in original ordern" ; 19 20 21 22 // output original array for ( int i = 0; i < array. Size; i++ ) cout << setw( 4 ) << a[ i ]; 23 49

24 25 26 27 28 29 30 31 32 33 34 35 36 37

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 // bubble sort Do // loop to control number of passes the for ( int pass = 0; pass < array. Size - 1; pass++ ) // loop to control number of comparisons per pass for ( int j = 0; j < array. Size - 1; j++ ) // compare side-by-side elements and swap them if // first element is greater than second element if ( a[ j ] > a[ j + 1 ] ) { hold = a[ j ]; a[ j ] = a[ j + 1 ]; a[ j + 1 ] = hold; } // end if a pass for each element in array. If the element on the left (index j) is larger than the element on the right (index j + 1), then we swap them. Remember the need of a temp variable. 50

40 cout << "n Data items in ascending ordern" ; 41 42 43 44

40 cout << "n Data items in ascending ordern" ; 41 42 43 44 // output sorted array for ( int k = 0; k < array. Size; k++ ) cout << setw( 4 ) << a[ k ]; 45 46 cout << endl; 47 48 return 0; // indicates successful termination 49 50 } // end main Data items in original order 2 6 4 8 10 12 89 68 45 37 Data items in ascending order 2 4 6 8 10 12 37 45 68 89 51

Computing Mean, Median and Mode Using Arrays • Mean – Average (sum/number of elements)

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) 52

1 2 // This program computes the mean, median, and mode of the data.

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

26 int frequency[ 10 ] = { 0 }; // initialize array frequency 27

26 int frequency[ 10 ] = { 0 }; // initialize array frequency 27 28 29 30 31 32 33 34 35 36 37 38 39 // initialize array responses int response[ response. Size ] = { 6, 7, 8, 9, 7, 8, 9, 5, 9, 8, 7, 8, 6, 7, 8, 9, 3, 9, 8, 7, 8, 9, 7, 8, 9, 6, 7, 8, 7, 9, 8, 9, 2, 7, 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 }; 40 41 42 43 44 // process responses mean( response, response. Size ); median( response, response. Size ); mode( frequency, response, response. Size ); 45 46 return 0; // indicates successful termination 47 48 } // end main 49 54

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 Meann****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 << "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" << "of data items (" << array. Size << "). The mean value forn this run is: " << total << " / " << array. Size << " = " << static_cast< double >( total ) / array. Size << "nn"; 72 73 } // end function mean We cast to a double to get decimal points for the average (instead of an integer). 74 55

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" ; 80 81 print. Array( answer, size ); // output unsorted array 82 83 bubble. Sort( answer, size ); // sort array 84 85 86 87 88 89 90 91 92 cout << "nn The sorted array is" ; print. Array( answer, size ); // output sorted array // display median element cout << "nn The median is element " << size / 2 << " ofn the sorted " << size << " element array. n For this run the median is " << answer[ size / 2 ] << "nn"; 93 94 } // end function median Sort array by passing it to a function. This keeps the program modular. 95 56

96 97 98 99 100 // determine most frequent response void mode( int freq[],

96 97 98 99 100 // determine most frequent response void mode( int freq[], int answer[], int size ) { int largest = 0; // represents largest frequency int mode. Value = 0; // represents most frequent response 101 102 cout << "n****n Moden****n" ; 103 104 // initialize frequencies to 0 105 for ( int i = 1; i <= 9; i++ ) 106 freq[ i ] = 0; 107 108 // summarize frequencies 109 for ( int j = 0; j < size; j++ ) 110 ++freq[ answer[ j ] ]; 111 112 113 114 115 116 // output headers for result columns cout << "Response" << setw( 11 ) << "Frequency" << setw( 19 ) << "Histogramnn" << setw( 55 ) << "1 1 2 2n" << setw( 56 ) << "5 0 5nn" ; 117 57

118 119 120 121 // output results for ( int rating = 1; rating

118 119 120 121 // output results for ( int rating = 1; rating <= 9; rating++ ) { cout << setw( 8 ) << rating << setw( 11 ) << freq[ rating ] << " "; 122 123 124 125 126 127 128 // keep track of mode value and largest frequency value if ( freq[ rating ] > largest ) { largest = freq[ rating ]; mode. Value = rating; } // end if The mode is the value that occurs most often (has the highest value in freq). 129 130 // output histogram bar representing frequency value 131 for ( int k = 1; k <= freq[ rating ]; k++ ) 132 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 58

144 145 146 147 148 // function that sorts an array with bubble sort

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

166 167 168 169 // output array contents (20 values per row) void print.

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

**** 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 array is 1 2 2 2 3 3 4 4 4 5 5 5 5 6 6 6 6 6 7 7 7 7 7 7 8 8 8 8 8 8 8 9 9 9 9 9 The median is element 49 of the sorted 99 element array. For this run the median is 7 61

**** Mode **** Response Frequency Histogram 1 1 2 2 5 0 5 1

**** Mode **** Response Frequency Histogram 1 1 2 2 5 0 5 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. 62

Searching Arrays: Linear Search and Binary Search • Search array for a key value

Searching Arrays: Linear Search and Binary Search • Search array for a key value • Linear search – Compare each element of array with key value • Start at one end, go to other – Useful for small and unsorted arrays • Inefficient • If search key not present, examines every element 63

1 2 3 // Linear search of an array. #include <iostream> 4 5 6

1 2 3 // Linear search of an array. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 int linear. Search( const int [], int ); // prototype 10 11 12 13 14 15 int main() { const int array. Size = 100; // size of array a int a[ array. Size ]; // create array a int search. Key; // value to locate in a 16 17 18 for ( int i = 0; i < array. Size; i++ ) // create some data a[ i ] = 2 * i; 19 20 21 cout << "Enter integer search key: " ; cin >> search. Key; 22 23 24 // attempt to locate search. Key in array a int element = linear. Search( a, search. Key, array. Size ); Takes array, search key, and array size. 25 64

26 27 28 29 30 // display results if ( element != -1 )

26 27 28 29 30 // display results if ( element != -1 ) cout << "Found value in element " << element << endl; else cout << "Value not found" << endl; 31 32 return 0; // indicates successful termination 33 34 } // end main 35 36 37 38 39 40 41 42 43 44 45 46 47 48 // compare key to every element of array until location is // found or until end of array is reached; return subscript of // element if key or -1 if key not found int linear. Search( const int array[], int key, int size. Of. Array ) { for ( int j = 0; j < size. Of. Array; j++ ) if ( array[ j ] == key ) // if found, return j; // return location of key return -1; // key not found } // end function linear. Search 65

Enter integer search key: 36 Found value in element 18 Enter integer search key:

Enter integer search key: 36 Found value in element 18 Enter integer search key: 37 Value not found 66

Searching Arrays: Linear Search and Binary Search • Binary search – Only used with

Searching Arrays: Linear Search and Binary Search • Binary search – Only used with sorted arrays – Compare middle element with key • If equal, match found • If key < middle – Repeat search on first half of array • If key > middle – Repeat search on last half – Very fast • At most N steps, where 2 N > # of elements • 30 element array takes at most 5 steps 5 2 > 30 67

1 2 3 // Binary search of an array. #include <iostream> 4 5 6

1 2 3 // Binary search of an array. #include <iostream> 4 5 6 7 using std: : cout; using std: : cin; using std: : endl; 8 9 #include <iomanip> 10 11 using std: : setw; 12 13 14 15 16 // function prototypes int binary. Search( const int [], int, int ); void print. Header( int ); void print. Row( const int [], int, int ); 17 18 19 20 21 22 int main() { const int array. Size = 15; // size of array a int a[ array. Size ]; // create array a int key; // value to locate in a 23 24 25 for ( int i = 0; i < array. Size; i++ ) // create some data a[ i ] = 2 * i; 26 68

27 28 cout << "Enter a number between 0 and 28: " ; cin

27 28 cout << "Enter a number between 0 and 28: " ; cin >> key; 29 30 print. Header( array. Size ); 31 32 33 34 // search for key in array a int result = binary. Search( a, key, 0, array. Size - 1, array. Size ); 35 36 37 38 39 40 41 // display results if ( result != -1 ) cout << 'n' << key << " found in array element " << result << endl; else cout << 'n' << key << " not found" << endl; 42 43 return 0; // indicates successful termination 44 45 } // end main 46 69

47 48 49 50 51 52 53 54 55 56 57 58 59 60

47 48 49 50 51 52 53 54 55 56 57 58 59 60 // function to perform binary search of an array int binary. Search( const int b[], int search. Key, int low, int high, int size ) { int middle; // loop until low subscript is greater than high subscript while ( low <= high ) { Determine middle element // determine middle element of subarray being searched middle = ( low + high ) / 2; // display subarray used in this loop iteration print. Row( b, low, middle, high, size ); 61 70

62 63 64 // if search. Key matches middle element, return middle if (

62 63 64 // if search. Key matches middle element, return middle if ( search. Key == b[ middle ] ) // match return middle; Use the 65 66 else 67 68 69 70 71 // if search. Key less than middle element, // set new high element If greater, if ( search. Key < b[ middle ] ) high = middle - 1; // search low end of array 72 73 74 75 76 77 // if search. Key greater than middle element, // set new low element else low = middle + 1; // search high end of array } 78 79 return -1; // search. Key not found 80 81 } // end function binary. Search rule of binary search: If key equals middle, match If less, search low end search high end Loop sets low, middle and high dynamically. If searching the high end, the new low is the element above the middle. 71

82 83 84 85 86 // print header for output void print. Header( int

82 83 84 85 86 // print header for output void print. Header( int size ) { cout << "n Subscripts: n"; 87 88 89 90 // output column heads for ( int j = 0; j < size; j++ ) cout << setw( 3 ) << j << ' '; 91 92 cout << 'n'; // start new line of output 93 94 95 96 // output line of - characters for ( int k = 1; k <= 4 * size; k++ ) cout << '-'; 97 98 cout << endl; // start new line of output 99 100 } // end function print. Header 101 72

102 103 104 105 106 107 108 // print one row of output showing

102 103 104 105 106 107 108 // print one row of output showing the current // part of the array being processed void print. Row( const int b[], int low, int mid, int high, int size ) { // loop through entire array for ( int m = 0; m < size; m++ ) 109 110 // display spaces if outside current subarray range 111 if ( m < low || m > high ) 112 cout << " "; 113 114 // display middle element marked with a * 115 else 116 117 if ( m == mid ) // mark middle value 118 cout << setw( 3 ) << b[ m ] << '*'; 119 120 // display other elements in subarray 121 else 122 cout << setw( 3 ) << b[ m ] << ' '; 123 124 cout << endl; // start new line of output 125 126 } // end function print. Row 73

 Enter a number between 0 and 28: 6 Subscripts: 0 1 2 3

Enter a number between 0 and 28: 6 Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ------------------------------ 0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 0 2 4 6* 8 10 12 6 found in array element 3 Enter a number between 0 and 28: 25 Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ------------------------------ 0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 16 18 20 22* 24 26 28 24 26* 28 24* 25 not found 74

Enter a number between 0 and 28: 8 Subscripts: 0 1 2 3 4

Enter a number between 0 and 28: 8 Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ------------------------------ 0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 0 2 4 6* 8 10 12 8 10* 12 8* 8 found in array element 4 75

Multiple-Subscripted Arrays • Multiple subscripts – – int a[ 2 ][ 3 ]; Tables

Multiple-Subscripted Arrays • Multiple subscripts – – int a[ 2 ][ 3 ]; 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 1 Column 2 Column 3 a[ 0 ][ 1 ] a[ 0 ][ 2 ] 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 Row subscript 76

Multiple-Subscripted Arrays • To initialize – Default of 0 – Initializers grouped by row

Multiple-Subscripted Arrays • To initialize – Default of 0 – Initializers grouped by row in braces int b[ 2 ] = { { 1, 2 }, { 3, 4 } }; Row 0 Row 1 (or int b[][2] = …) int b[ 2 ] = { { 1 }, { 3, 4 } }; (or int b[][2] = …) 1 2 3 4 1 0 3 4 77

Multiple-Subscripted Arrays • Referenced like normal cout << b[ 0 ][ 1 ]; 1

Multiple-Subscripted Arrays • Referenced like normal cout << b[ 0 ][ 1 ]; 1 0 3 4 – Outputs 0 – Cannot reference using commas cout << b[ 0, 1 ]; • Function prototypes – Must specify sizes of subscripts • First subscript not necessary, as with single-scripted arrays – void print. Array( int [][ 3 ] ); 78

1 2 3 // Initializing multidimensional arrays. #include <iostream> Note the format of the

1 2 3 // Initializing multidimensional arrays. #include <iostream> 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 } }; 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; // indicates successful termination 26 27 } // end main Note the various initialization styles. The elements in array 2 are assigned to the first row and then the second. 79

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 // function to output array with two rows and three columns void print. Array( int a[][ 3 ] ) { for ( int i = 0; i < 2; i++ ) { // for each row for ( int j = 0; j < 3; j++ ) // output column values cout << a[ i ][ j ] << ' '; cout << endl; // 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 For loops are often used to iterate through arrays. Nested loops are helpful with multiple-subscripted arrays. 80

Multiple-Subscripted Arrays • Program to keep track of students grades – Main data structure

Multiple-Subscripted Arrays • Program to keep track of students grades – Main data structure • Multiple-subscripted array (table) • Rows are students • Columns are grades Quiz 1 Quiz 2 Student 0 95 85 Student 1 89 80 81

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 std: : cout; using std: : endl; using std: : fixed; using std: : left; 9 10 #include <iomanip> 11 12 13 using std: : setw; using std: : setprecision; 14 15 16 const int students = 3; // number of students const int exams = 4; // number of exams 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 ); 23 82

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 } }; 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: " << maximum( student. Grades, students, exams ) << 'n'; 41 42 cout << fixed << setprecision( 2 ); 43 83

44 45 46 47 48 49 // calculate average grade for each student for

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; // indicates successful termination 52 53 } // end main 54 55 56 57 58 // find minimum grade int minimum( int grades[][ exams ], int pupils, int tests ) { int low. Grade = 100; // initialize to highest possible grade 59 60 for ( int i = 0; i < pupils; i++ ) 61 62 for ( int j = 0; j < tests; j++ ) 63 64 65 if ( grades[ i ][ j ] < low. Grade ) low. Grade = grades[ i ][ j ]; 66 67 return low. Grade; 68 69 } // end function minimum Determines the average for one student. We pass the array/row containing the student’s grades. Note that student. Grades[0] is itself an array. 84

70 71 72 73 74 // find maximum grade int maximum( int grades[][ exams

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

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; // 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 86

99 100 101 102 103 104 // Print the array void print. Array( int

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

The array is: [0] [1] [2] [3] student. Grades[0] 77 68 86 73 student.

The array is: [0] [1] [2] [3] student. Grades[0] 77 68 86 73 student. Grades[1] 96 87 89 78 student. Grades[2] 70 90 86 81 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 88

End of Arrays! • Next week Midterm Exam on Thursday • On Tuesday Abstract

End of Arrays! • Next week Midterm Exam on Thursday • On Tuesday Abstract Data Types (not on midterm) 89