1 2 3 Fig 4 3 fig 0403

  • Slides: 79
Download presentation

1 2 3 // Fig. 4. 3: fig 04_03. cpp // Initializing an array.

1 2 3 // Fig. 4. 3: fig 04_03. cpp // 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() { Initialize array to 0 using a for int n[ 10 ]; // n is an array of 10 integers 15 16 17 18 19 20 21 22 23 24 25 Outline Declare a 10 -element array of integers. loop. Note that the array has elements n[0] to n[9]. // initialize elements of array n to 0 Ο χειριστής setw (για τη for ( int i = 0; i < 10; i++ ) n[ i ] = 0; // set element at location i to 0 χρήση του πρέπει να ενσωματωθεί το αρχείο cout << "Element" << setw( 13 ) << "Value" << endl; iomanip. h) αναγκάζει τον αριθμό ή το αλφαριθμητικό // output contents of array n in tabular format που τον ακολουθεί να for ( int j = 0; j < 10; j++ ) τυπωθεί μέσα σε ένα πεδίο cout << setw( 7 ) << j << setw( 13 ) << n[ j ] << endl; πλάτους n, όπου n το όρισμα του setw(n). fig 04_03. cpp (1 of 2) 2003 Prentice Hall, Inc. All rights reserved. 9

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

26 return 0; // indicates successful termination 27 28 } // end main Element Value 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 Outline fig 04_03. cpp (2 of 2) fig 04_03. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 10

1 2 3 // Fig. 4. 4: fig 04_04. cpp // Initializing an array

1 2 3 // Fig. 4. 4: fig 04_04. cpp // 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 Note the use of the initializer 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 Outline fig 04_04. cpp (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 11

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 Outline fig 04_04. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 12

1 2 3 // Fig. 4. 5: fig 04_05. cpp // Initialize array s

1 2 3 // Fig. 4. 5: fig 04_05. cpp // 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() Only const variables can { specify array sizes. // constant variable can be used to specify array size const int array. Size = 10; The program becomes more scalable when we set the array int s[ array. Size ]; // array s has 10 elements 18 19 20 21 22 23 Outline Note use of const keyword. fig 04_05. cpp (1 of 2) size using a const variable. We can change array. Size, for ( int i = 0; i < array. Size; i++ ) // set the values s[ i ] = 2 + 2 * i; and all the loops will still work (otherwise, we’d have to cout << "Element" << setw( 13 ) << "Value" << endl; update every loop in the program). 2003 Prentice Hall, Inc. All rights reserved. 14

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 Value 0 2 1 4 2 6 3 8 4 10 5 12 6 14 7 16 8 18 9 20 Outline fig 04_05. cpp (2 of 2) fig 04_05. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 15

1 2 3 // Fig. 4. 6: fig 04_06. cpp // Using a properly

1 2 3 // Fig. 4. 6: fig 04_06. cpp // Using a properly initialized constant variable. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 10 int main() { const int x = 7; // initialized constant variable 11 12 13 cout << "The value of constant variable x is: " << x << endl; 14 15 return 0; // indicates successful termination 16 17 } // end main Outline Proper initialization of const variable. fig 04_06. cpp (1 of 1) fig 04_06. cpp output (1 of 1) The value of constant variable x is: 7 2003 Prentice Hall, Inc. All rights reserved. 16

1 2 // Fig. 4. 7: fig 04_07. cpp // A const object must

1 2 // Fig. 4. 7: fig 04_07. cpp // A const object must be initialized. 3 4 5 6 Uninitialized const results in a syntax error. Attempting int main() to modify the const is { const int x; // Error: x must be initialized another error. 7 8 x = 7; // Error: cannot modify a const variable 9 10 return 0; // indicates successful termination 11 12 } // end main d: cpphtp 4_examplesch 04Fig 04_07. cpp(6) : error C 2734: 'x' : const object must be initialized if not extern d: cpphtp 4_examplesch 04Fig 04_07. cpp(8) : error C 2166: l-value specifies const object Outline fig 04_07. cpp (1 of 1) fig 04_07. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 17

1 2 3 // Fig. 4. 8: fig 04_08. cpp // Compute the sum

1 2 3 // Fig. 4. 8: fig 04_08. cpp // 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 Outline fig 04_08. cpp (1 of 1) fig 04_08. cpp output (1 of 1) Total of array element values is 55 2003 Prentice Hall, Inc. All rights reserved. 18

1 2 3 // Fig. 4. 9: fig 04_09. cpp // Histogram printing program.

1 2 3 // Fig. 4. 9: fig 04_09. cpp // 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 << '*'; Outline fig 04_09. cpp (1 of 2) n[i]. 2003 Prentice Hall, Inc. All rights reserved. 19

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 Value Histogram 0 19 ********** 1 3 *** 2 15 ******** 3 7 ******* 4 11 ****** 5 9 ***** 6 13 ******* 7 5 ***** 8 17 ********* 9 1 * Outline fig 04_09. cpp (2 of 2) fig 04_09. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 20

1 2 3 // Fig. 4. 10: fig 04_10. cpp // Roll a six-sided

1 2 3 // Fig. 4. 10: fig 04_10. cpp // 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> Outline 19 20 fig 04_10. cpp (1 of 2) Remake of old program to roll int main() dice. An array is used instead { of 6 regular variables, and the const int array. Size = 7; proper element can be updated int frequency[ array. Size ] = { 0 }; easily (without needing a srand( time( 0 ) ); // seed random-number generator switch). 21 22 23 24 25 // roll die 6000 times This creates a number for ( int roll = 1; roll <= 6000; roll++ ) between 1 and 6, which ++frequency[ 1 + rand() % 6 ]; // replaces 20 -line switch determines the index of // of Fig. 3. 8 14 15 16 17 18 frequency[] that should be incremented. 2003 Prentice Hall, Inc. All rights reserved. 21

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 Frequency 1 1003 2 1004 3 999 4 980 5 1013 6 1001 Outline fig 04_10. cpp (2 of 2) fig 04_10. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 23

1 2 3 // Fig. 4_12: fig 04_12. cpp // Treating character arrays as

1 2 3 // Fig. 4_12: fig 04_12. cpp // 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 13 14 15 16 Outline Two different ways to declare strings. string 2 is int main() { initialized, and its size char string 1[ 20 ], // reserves 20 characters determined automatically. char string 2[] = "string literal"; // reserves 15 characters Examples of reading strings from the keyboard and // read string from user into array string 2 cout << "Enter the string "hello there": " ; printing them out. fig 04_12. cpp (1 of 2) 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" ; 23 2003 Prentice Hall, Inc. All rights reserved. 26

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" string using array notation. cout << "nstring 1 is: " << string 1 << endl; Outline Can access the characters in a 30 31 The loop ends when the null character is found. return 0; // indicates successful termination 32 33 } // end main Enter the string "hello there": hello there string 1 is: hello string 2 is: string literal string 1 with spaces between characters is: h e l l o string 1 is: there fig 04_12. cpp (2 of 2) fig 04_12. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 27

1 2 3 // Fig. 4. 13: fig 04_13. cpp // Static arrays are

1 2 3 // Fig. 4. 13: fig 04_13. cpp // 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 Outline fig 04_13. cpp (1 of 3) 25 2003 Prentice Hall, Inc. All rights reserved. 29

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 to zero 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 Array data is changed; the modified values stay. Outline fig 04_13. cpp (2 of 3) 46 2003 Prentice Hall, Inc. All rights reserved. 30

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 ) Automatic array, recreated { with every function call. // 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 Although the array is changed, it will be destroyed when the function exits and the changes will be lost. Outline fig 04_13. cpp (3 of 3) 2003 Prentice Hall, Inc. All rights reserved. 31

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 Outline 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 fig 04_13. cpp output (1 of 1) 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 2003 Prentice Hall, Inc. All rights reserved. 32

1 2 3 // Fig. 4. 14: fig 04_14. cpp // Passing arrays and

1 2 3 // Fig. 4. 14: fig 04_14. cpp // 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 ]; Outline Syntax for accepting an array in parameter list. fig 04_14. cpp (1 of 3) 2003 Prentice Hall, Inc. All rights reserved. 36

26 27 cout << endl; 28 29 30 31 32 modify. Array( a, array.

26 27 cout << endl; 28 29 30 31 32 modify. Array( a, array. Size ); cout << "The values of the modified array are: n" ; Pass array name (a) and size to function. Arrays are passed -by-reference. // pass array a to modify. Array by reference 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: " Pass a single array element by << "nn. The value of a[3] is " << a[ 3 ] << 'n'; 42 43 44 modify. Element( a[ 3 ] ); Outline fig 04_14. cpp (2 of 3) value; the original cannot be modified. // pass array element a[ 3 ] by value 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 2003 Prentice Hall, Inc. All rights reserved. 37

52 53 54 55 56 57 58 59 60 61 62 63 64 65

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 // 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 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 // in function modify. Element, "e" is a local copy of originals cannot be changed. // 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 Outline fig 04_14. cpp (3 of 3) 2003 Prentice Hall, Inc. All rights reserved. 38

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 Outline 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 fig 04_14. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 39

1 2 3 // Fig. 4. 15: fig 04_15. cpp // Demonstrating the const

1 2 3 // Fig. 4. 15: fig 04_15. cpp // Demonstrating the const type qualifier. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 Array parameter declared as const. Array cannot be modified, even though it is passed by reference. void try. To. Modify. Array( const int [] ); // function prototype 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 Outline fig 04_15. cpp (1 of 2) 21 2003 Prentice Hall, Inc. All rights reserved. 40

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 d: cpphtp 4_examplesch 04Fig 04_15. cpp(26) : error C 2166: l-value specifies const object d: cpphtp 4_examplesch 04Fig 04_15. cpp(27) : error C 2166: l-value specifies const object d: cpphtp 4_examplesch 04Fig 04_15. cpp(28) : error C 2166: l-value specifies const object Outline fig 04_15. cpp (2 of 2) fig 04_15. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 41

1 2 3 // Fig. 4. 16: fig 04_16. cpp // This program sorts

1 2 3 // Fig. 4. 16: fig 04_16. cpp // 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 ]; Outline fig 04_16. cpp (1 of 3) 23 2003 Prentice Hall, Inc. All rights reserved. 45

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 // bubble sort Do a pass for each element in // loop to control number of passes the array. for ( int pass = 0; pass < array. Size; 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 If the element on the left // first element is greater than second element (index j) is larger than the if ( a[ j ] > a[ j + 1 ] ) { element on the right (index j hold = a[ j ]; + 1), then we swap them. a[ j ] = a[ j + 1 ]; Remember the need of a temp fig 04_16. cpp a[ j + 1 ] = hold; variable. (2 of 3) } // end if Outline 39 2003 Prentice Hall, Inc. All rights reserved. 46

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 Outline fig 04_16. cpp (3 of 3) fig 04_16. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 47

1 2 3 // Fig. 4. 19: fig 04_19. cpp // Linear search of

1 2 3 // Fig. 4. 19: fig 04_19. cpp // 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 ); Outline Takes array, search key, and array size. fig 04_19. cpp (1 of 2) 25 2003 Prentice Hall, Inc. All rights reserved. 50

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 Outline fig 04_19. cpp (2 of 2) 2003 Prentice Hall, Inc. All rights reserved. 51

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

Enter integer search key: 36 Found value in element 18 Outline Enter integer search key: 37 Value not found fig 04_19. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 52

1 2 3 // Fig. 4. 20: fig 04_20. cpp // Binary search of

1 2 3 // Fig. 4. 20: fig 04_20. cpp // 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; Outline fig 04_20. cpp (1 of 6) 26 2003 Prentice Hall, Inc. All rights reserved. 53

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 Outline fig 04_20. cpp (2 of 6) 46 2003 Prentice Hall, Inc. All rights reserved. 54

47 48 49 50 51 // function to perform binary search of an array

47 48 49 50 51 // 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; 52 53 54 // loop until low subscript is greater than high subscript Determine middle element while ( low <= high ) { 55 56 57 // determine middle element of subarray being searched middle = ( low + high ) / 2; 58 59 60 // display subarray used in this loop iteration print. Row( b, low, middle, high, size ); Outline fig 04_20. cpp (3 of 6) 61 2003 Prentice Hall, Inc. All rights reserved. 55

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; 65 66 else 67 68 69 70 71 If less, search low end // if search. Key less than middle element, // set new high element If greater, search high end 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, high dynamically. If searching // set new low element the high end, the new low is else the element above the middle. low = middle + 1; // search high end of array } 78 79 return -1; // search. Key not found 80 81 } // end function binary. Search Outline Use the rule of binary search: If key equals middle, match Loop sets low, middle and fig 04_20. cpp (4 of 6) 2003 Prentice Hall, Inc. All rights reserved. 56

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 Outline fig 04_20. cpp (5 of 6) 99 100 } // end function print. Header 101 2003 Prentice Hall, Inc. All rights reserved. 57

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++ ) Outline 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 fig 04_20. cpp (6 of 6) 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 2003 Prentice Hall, Inc. All rights reserved. 58

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

Enter a number between 0 and 28: 6 Outline 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 fig 04_20. cpp output (1 of 2) 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 2003 Prentice Hall, Inc. All rights reserved. 59

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* Outline 8 found in array element 4 fig 04_20. cpp output (2 of 2) 2003 Prentice Hall, Inc. All rights reserved. 60

47 48 49 50 51 // Recursive function to perform binary search of an

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

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; 65 66 else 67 68 69 70 71 If less, search low end // if search. Key less than middle element, // search low end of array If greater, search high end if ( search. Key < b[ middle ] ) return rbinary. Search(b, search. Key, low, middle– 1, size); Outline Use the rule of binary search: If key equals middle, match Recursive step sets low, 72 middle and high dynamically. 73 // if search. Key greater than middle element, If searching the high end, the 74 // search high end of array 75 else return rbinary. Search(b, search. Key, middle+1, high, new low is the element above size); the middle. 77 } 78 79 return -1; // search. Key not found 80 81 } // end function rbinary. Search 2003 Prentice Hall, Inc. All rights reserved. 63

1 2 3 // Fig. 4. 22: fig 04_22. cpp // Initializing multidimensional arrays.

1 2 3 // Fig. 4. 22: fig 04_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 } }; 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. fig 04_22. cpp (1 of 2) 2003 Prentice Hall, Inc. All rights reserved. 67

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++ ) // 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: 1 2 3 4 5 6 Values in array 2 by row are: 1 2 3 4 5 0 Values in array 3 by row are: 1 2 0 4 0 0 Outline fig 04_22. cpp (2 of 2) fig 04_22. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 68

1 2 3 // Fig. 4. 23: fig 04_23. cpp // Double-subscripted array example.

1 2 3 // Fig. 4. 23: fig 04_23. cpp // 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 ); Outline fig 04_23. cpp (1 of 6) 23 2003 Prentice Hall, Inc. All rights reserved. 70

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 ); Outline fig 04_23. cpp (2 of 6) 43 2003 Prentice Hall, Inc. All rights reserved. 71

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 54 55 56 57 58 Determines the average for one student. We pass the array/row containing the } // end main student’s grades. Note that student. Grades[0] is // find minimum grade itself an array. 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 Outline fig 04_23. cpp (3 of 6) 2003 Prentice Hall, Inc. All rights reserved. 72

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 Outline fig 04_23. cpp (4 of 6) 86 2003 Prentice Hall, Inc. All rights reserved. 73

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 Outline fig 04_23. cpp (5 of 6) 2003 Prentice Hall, Inc. All rights reserved. 74

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]" ; Outline 105 106 // output grades in tabular format 107 for ( int i = 0; i < pupils; i++ ) { 108 109 // output label for row 110 cout << "nstudent. 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 ]; fig 04_23. cpp (6 of 6) 115 116 } // end outer for 117 118 } // end function print. Array 2003 Prentice Hall, Inc. All rights reserved. 75

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 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 fig 04_23. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 76

77 Αναφορές • Harvey M. Deitel, Paul J. Deitel, C++ How to Program, 4

77 Αναφορές • Harvey M. Deitel, Paul J. Deitel, C++ How to Program, 4 th Edition, Prentice Hall. • Bjarne Stroustrup, The C++ Programming Language, Special Edition, Addison-Wesley.