1 Arrays Outline Examples Using Arrays Passing arrays

  • Slides: 44
Download presentation
1 Arrays Outline Examples Using Arrays Passing arrays to functions Class Grade. Book: store

1 Arrays Outline Examples Using Arrays Passing arrays to functions Class Grade. Book: store student grades Searching Arrays—Linear search Sorting Arrays Midterm Solution 2003 Prentice Hall, Inc. All rights reserved.

Using character arrays to store and manipulate strings • string has been used to

Using character arrays to store and manipulate strings • string has been used to store character strings – A string such as “Hello” is an array of characters • A character array can be declared and initialized as: – char string 1[] = “first”; – The size of array string 1 is not explicitly defined, but it is determined by the compiler based on the length of the string. – NOTE: • all strings represented by a character array ends with a special character (the null character ‘’) • A character array representing a string should be defined large enough to hold the number of characters in the string + the termination character 2003 Prentice Hall, Inc. All rights reserved. 2

Using character arrays to store and manipulate strings • One could also use this

Using character arrays to store and manipulate strings • One could also use this method to declare strings: char string 1[] = {‘f’, ‘i’, ‘r’, ‘s’, ‘t’, ‘’}; If you don’t use ‘’, the array would simply represent an array of characters, not a string! if you specify the size of string 1 and the size of “list of initializers” is larger syntax error • char arrays can be manipulated as other arrays, example: – string[0] = ‘f’; 2003 Prentice Hall, Inc. All rights reserved. 3

Using character arrays to store and manipulate strings • Input from keyboard char string

Using character arrays to store and manipulate strings • Input from keyboard char string 2[ 20 ]; cin >> string 2; – Puts user input in string • Stops at first whitespace character • Adds null character – If too much text entered, data written beyond array • We want to avoid this • Printing strings – cout << string 2 << endl; • Does not work for other array types – Characters printed until null found 2003 Prentice Hall, Inc. All rights reserved. 4

1 2 3 4 5 6 // Fig. 7. 12: fig 07_12. cpp //

1 2 3 4 5 6 // Fig. 7. 12: fig 07_12. cpp // treating character arrays as strings. #include <iostream> using std: : cout; using std: : cin; using std: : endl; Outline 7 8 int main() 9 { 10 char string 1 [20]; // reserve 20 characters 11 char string 2 [] = “string literal”; // reserve 15 characters 12 13 14 15 // read string from user into array string 1 cout << “Enter the string “hello there”: ” ; cin >> string 1; // read “hello” [space terminates input] 16 17 18 19 // output strings cout << “string 1 is: ” << string 1 << “nstring 2 is: ” << string 2; cout << “nstring 1 with spaces between characters is: n” ; 20 21 22 23 // output characters until null character is reached for ( int i = 0; string 1[ i ]!= ‘’; i++ ) cout << string 1[ i ] << ‘ ’; 24 25 26 cin >> string 1; // reads “there” cout << “nstring 1 is: ” << string 1 <<endl; 27 28 29 return 0; // indicates successful termination } // end main 2003 Prentice Hall, Inc. All rights reserved. 5

Enter the string “hello there”: hello there string 1 is: hello string 2 is:

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 Outline 2003 Prentice Hall, Inc. All rights reserved. 6

7 Static and automatic local variables • Recall static storage – If static, local

7 Static and automatic local variables • 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 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 7. 13: fig 07_13. cpp // Static arrays are

1 2 3 // Fig. 7. 13: fig 07_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 ); void automatic. Array. Init( void ); 10 11 12 13 14 15 int main() { cout << "First call to each function: n" ; static. Array. Init(); automatic. Array. Init(); // function prototype 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; 23 24 Outline // indicates successful termination } // end main 25 2003 Prentice Hall, Inc. All rights reserved. 8

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 for ( int j = 0; j < cout << "array 1[" << ( array 1[ 44 45 Outline "; Array data is changed; the modified values stay. contents of array 1 3; j++ ) << j << "] = " j ] += 5 ) << " "; } // end function static. Array. Init 46 2003 Prentice Hall, Inc. All rights reserved. 9

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 for ( int j = 0; j < cout << "array 2[" << ( array 2[ 65 66 contents of array 2 3; j++ ) << j << "] = " j ] += 5 ) << " "; Outline "; Although the array is changed, it will be destroyed when the function exits and the changes will be lost. } // end function automatic. Array. Init 2003 Prentice Hall, Inc. All rights reserved. 10

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

First call to each function: Values on array 1[0] entering static. Array. Init: = 0 array 1[1] = 0 array 1[2] = 0 exiting static. Array. Init: = 5 array 1[1] = 5 array 1[2] = 5 Values on array 2[0] entering automatic. Array. Init: = 1 array 2[1] = 2 array 2[2] = 3 exiting automatic. Array. Init: = 6 array 2[1] = 7 array 2[2] = 8 Outline Second call to each function: Values on array 1[0] entering static. Array. Init: = 5 array 1[1] = 5 array 1[2] = 5 exiting static. Array. Init: = 10 array 1[1] = 10 array 1[2] = 10 Values on array 2[0] entering automatic. Array. Init: = 1 array 2[1] = 2 array 2[2] = 3 exiting automatic. Array. Init: = 6 array 2[1] = 7 array 2[2] = 8 2003 Prentice Hall, Inc. All rights reserved. 11

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

12 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 2003 Prentice Hall, Inc. All rights reserved.

13 Passing Arrays to Functions • Arrays passed-by-reference – Functions can modify original array

13 Passing Arrays to Functions • Arrays passed-by-reference – Functions can modify original array data – 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 passed-by-value – Like regular variables – square( my. Array[3] ); 2003 Prentice Hall, Inc. All rights reserved.

14 Passing Arrays to Functions • Functions taking arrays – Function prototype • void

14 Passing Arrays to Functions • Functions taking arrays – Function prototype • 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 (compiler error) • void do. Not. Modify( const int [] ); 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 7. 14: fig 07_14. cpp // Passing arrays and

1 2 3 // Fig. 7. 14: fig 07_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 ); void modify. Element( int ); 14 15 16 17 18 int main() { const int array. Size = 5; int a[ array. Size ] = { 0, 1, 2, 3, 4 }; Outline Syntax for accepting an array in parameter list. // appears strange // size of array a // 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 ]; 2003 Prentice Hall, Inc. All rights reserved. 15

26 27 28 29 30 31 32 cout << endl; // pass array a

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

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; Although named b, the array points to the original array a. It can modify a’s data. Outline } // end function modify. Array Individual array elements are passed in function modify. Element, "e" is a local copybyofvalue, and the array element a[ 3 ] passed from main originals cannot be changed. // // void modify. Element( int e ) { // multiply parameter by 2 cout << "Value in modify. Element is " << ( e *= 2 ) << endl; } // end function modify. Element 2003 Prentice Hall, Inc. All rights reserved. 17

Effects of passing entire array by reference: The values of 0 1 2 3

Effects of passing entire array by reference: The values of 0 1 2 3 The values of 0 2 4 6 Outline the original array are: 4 the modified array are: 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 2003 Prentice Hall, Inc. All rights reserved. 18

1 2 3 // Fig. 7. 15: fig 07_15. cpp // Demonstrating the const

1 2 3 // Fig. 7. 15: fig 07_15. cpp // 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; 19 20 // Outline Array parameter declared as const. Array cannot be modified, even though it is passed byprototype reference. function // indicates successful termination } // end main 21 2003 Prentice Hall, Inc. All rights reserved. 19

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 Outline } // end function try. To. Modify. Array d: cpphtp 7_examplesch 07Fig 07_15. cpp(26) : error C 2166: l-value specifies const object d: cpphtp 7_examplesch 07Fig 07_15. cpp(27) : error C 2166: l-value specifies const object d: cpphtp 7_examplesch 07Fig 07_15. cpp(28) : error C 2166: l-value specifies const object 2003 Prentice Hall, Inc. All rights reserved. 20

Class Grade. Book: store student grades Outline 1 // Grade. Book. h 2 //

Class Grade. Book: store student grades Outline 1 // Grade. Book. h 2 // Definition of class Grade. Book that uses an array to store test grades 3 // Member functions are defined in Grade. Book. cpp 4 5 #include <string> 6 using std: : string; 7 // Grade. Book Class definition 8 Class Grade. Book Defined as public: it is 9 { accessible to the user of the 10 public: 11 // const. Number of students who took class the test 12 const static int students = 10; 13 // constructor initializes course. Name 14 Grade. Book( string, const int [] ); 15 void set. Course. Name(string); // Function that sets the course name 16 string get. Course. Name(); // Function that gets the course name 17 void display. Message(); // Function that displays a welcome message 18 void process. Grades(); // perform various operations on the grades 19 int get. Minimum(); // find the minimum grade of the test 20 int get. Maximum(); // find the maximum grade of the test 21 double get. Average(); // determine the average grade of the test 22 void output. Bar. Chart(); // output bar char for grade distribution 23 void output. Grades(); // output the content of the grades array 24 private: 25 string course. Name; // course name of this Grade. Book 26 int grades [students]; // array of student grades 27 }; // end class Grade. Book 2003 Prentice Hall, Inc. All rights reserved. 21

1 2 3 4 5 6 7 8 // Grade. Book. cpp // Member

1 2 3 4 5 6 7 8 // Grade. Book. cpp // Member function definitions for class Grade. Book that // uses array to store test grades #include <iostream> using std: : cout; using std: : cin; using std: : endl; using std: : fixed; 9 10 11 12 #include <iomanip> using std: : setprecision; using std: : setw; 13 14 #include “Grade. Book. h” 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 // Constructor initializes course. Name with string supplied as argument; // initializes counter data members to 0; Grade. Book: : Grade. Book(string name, cont int grades. Array[] ) { set. Course. Name(name); //initialize course. Name //copy grades from grade. Array to grades data member for ( int grade = 0; grade < students; grade ++ ) grades[ grade ] = grades. Array [ grade ]; } // End constructor // function to set the course name void Grade. Book: : set. Course. Name(string name) { course. Name = name; //store name in the course. Name } 2003 Prentice Hall, Inc. All rights reserved. 22

23 30 31 32 33 34 35 // Function that gets the course name

23 30 31 32 33 34 35 // Function that gets the course name String Grade. Book: : get. Course. Name () { return course. Name; // store the object’s course name } // end function get. Course. Name 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 // Function that displays a welcome message void Grade. Book: : display. Message () { // call get. Course. Name to get the course. Name cout << “Welcome to the grade book forn" << get. Course. Name()<<"!“ <<endl; } // end function display. Message Print contents of grades // perform various operation on thethe data void Grade. Book: : process. Gradesarray () { output. Grades(); // output grades array cout << “n. Class Average is "<< setprecision (2) << fixed << get. Average. Grade()<< endl; cout << “Lowest Grade is "<< get. Minimum() << “n. Highest Grade is "<< get. Maximum()<< endl; output. Bar. Chart(); // call function to print grade distribution } // end function process. Grades 2003 Prentice Hall, Inc. All rights reserved.

54 // find minimum grade 55 int Grade. Book: : get. Minimum() 56 {

54 // find minimum grade 55 int Grade. Book: : get. Minimum() 56 { 57 int low. Grade = 100 ; //assume lowest grade is 100 58 //loop through grades array 59 for ( int grade = 0; grade < students; grade ++ ) 60 { 61 //if current grade lower than low. Grade, assign it to low. Grade 62 if ( grades[ grade ] < low. Grade ) 63 low. Grade = grades[ grade ] ; 64 } 65 return low. Grade; 66 } 67 // find maximum grade 68 int Grade. Book: : get. Maximum() 69 { 70 int high. Grade = 0; //assume highest grade is 100 71 //loop through grades array 72 for ( int grade = 0; grade < students; grade ++ ) 73 { 74 //if current grade higher than high. Grade, assign it to high. Grade 75 if ( grades[ grade ] > high. Grade ) 76 high. Grade = grades[ grade ] ; 77 } 78 return high. Grade; 79 } 2003 Prentice Hall, Inc. All rights reserved. 24

80 81 82 83 84 85 86 87 88 89 90 // find average

80 81 82 83 84 85 86 87 88 89 90 // find average grade double Grade. Book: : get. Average() { int total = 0 ; //initialize total //sum grades in array for ( int grade = 0; grade < students; grade ++ ) { total += grades[ grade ] ; } return static_cast<double> (total)/student; } 2003 Prentice Hall, Inc. All rights reserved. 25

91 void Grade. Book: : output. Bar. Chart () 92 { 93 cout <<

91 void Grade. Book: : output. Bar. Chart () 92 { 93 cout << “Grade Distribution: " << endl; 94 const int frequency. Size = 11; 95 int frequency[frequency. Size] = { 0 }; 96 97 cout << “Grade Distribution: " << endl; 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 // for each grade frequency, print bar in chart for ( int count = 0; count < frequency. Size; count++ ) { if (count == 0) cout << “ 0 -9: ”; else if (count == 10) cout << “ 100: ”; else cout << count * 10 << “-” << (count * 10) + 9<< “: ”; // print bar of asterisks for ( int stars = 0; stars < frequency[ count ]; stars++ ) cout << '*'; Loop over the grades array, increment the counter for // for each grade increment the appropriate frequency that fall in the for ( int grade = 0; grade < students ; grade++grades ) appropriate range frequency [ grades [ grade ] / 10 ]++; 113 114 115 116 117 cout << endl; // start next line of output } } 2003 Prentice Hall, Inc. All rights reserved. 26

118 119 120 121 122 123 124 125 126 127 // output the contents

118 119 120 121 122 123 124 125 126 127 // output the contents of the grades array void Grade. Book: : output. Grades() { cout << “n. The Grades are: nn"; //output each student’s grade for ( int student = 0; student < students; student ++ ) cout << “Student "<< setw(2)<< student + 1 << “: " << setw(3) << grades[student]<<endl; } 2003 Prentice Hall, Inc. All rights reserved. 27

1 2 3 // figure 07_18. cpp // Create GRade. Book object using an

1 2 3 // figure 07_18. cpp // Create GRade. Book object using an array of grades #include “Grade. Book. h” // include definition of class Analysis 4 Size of array “students” is a 5 int main() public variable and it is 6 { accessed in the main function 7 // array of student grades 8 int grades. Array[ Grade. Book: : students ] = 9 {87, 68, 94, 100, 83, 78, 85, 91, 76, 87}; 10 Grade. Book my. Grade. Book(“MECH 215 Introduction to C++ Programming“ , grades. Array); 11 my. Grade. Book. display. Message (); 12 my. Grade. Book. process. Grades (); 13 return 0; 14 } // end main 2003 Prentice Hall, Inc. All rights reserved. 28

Welcome to the grade book for MECH 215 Introduction to C++ Programming! The grades

Welcome to the grade book for MECH 215 Introduction to C++ Programming! The grades are: Student 1: 87 Student 2: 68 Student 3: 94 Student 4: 100 Student 5: 83 Student 6: 78 Student 7: 85 Student 8: 91 Student 9: 76 Student 10: 87 Class average is 84. 90 Lowest grade is 68 Highest grade is 100 Grade 0 -9: 10 -19: 20 -29: 30 -39: 40 -49: 50 -59: 60 -69: 70 -79: 80 -89: 90 -99: 100: distribution * * * * * 2003 Prentice Hall, Inc. All rights reserved. 29

30 Searching Arrays—Linear search • Search array for a “key value” • Linear search

30 Searching Arrays—Linear search • Search array for a “key value” • Linear search – Compare each element of array with key value (search key) • The element we are searching for is likely to be at any position in the array • Start at one end, go to other – Useful for small and unsorted arrays • Inefficient • If search key not present, examines every element – Binary search improves efficiency • It works on sorted arrays 2003 Prentice Hall, Inc. All rights reserved.

31 Searching Arrays—Binary search • Binary search – Only used with sorted arrays –

31 Searching Arrays—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 25 > 30 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 7. 19: fig 07_19. cpp // Linear search of

1 2 3 // Fig. 7. 19: fig 07_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 ); 10 11 12 13 14 15 int main() { const int array. Size = 100; int a[ array. Size ]; int search. Key; Outline Takes array, search key, and array size. // prototype // size of array a // create array a // value to locate in a 16 17 18 for ( int i = 0; i < array. Size; i++ ) 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 ); // create some data 25 2003 Prentice Hall, Inc. All rights reserved. 32

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; 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 Outline // indicates successful termination } // end main // 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 ) return j; return -1; // if found, // return location of key // key not found } // end function linear. Search 2003 Prentice Hall, Inc. All rights reserved. 33

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 2003 Prentice Hall, Inc. All rights reserved. 34

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

35 Sorting Arrays • Sorting data – Important computing application – Virtually every organization must sort some data • Massive amounts must be sorted • Insertion 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 2003 Prentice Hall, Inc. All rights reserved.

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

36 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 2003 Prentice Hall, Inc. All rights reserved.

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

37 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, temp = x; x = y; y = temp; y = 4, temp; // temp gets 3 // x gets 4 // y gets 3 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 7. 20: fig 07_20. cpp // This program sorts

1 2 3 // Fig. 7. 20: fig 07_20. 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 23 2003 Prentice Hall, Inc. All rights reserved. 38

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 Outline // loop to control number of passes for ( i = 0; i < array. Size; i++ ) // loop to control number of comparisons per pass for ( int j = i+1; j < array. Size; j++ ) // compare side-by-side elements and swap them if element on the left If the // first element is greater than second element (index j) is smaller than the if ( a[ j ] < a[ i ] ) { element on the right (index i), hold = a[ j ]; then we swap them. a[ j ] = a[ i ]; Remember the need of a temp a[ i ] = hold; variable. } // end if 39 2003 Prentice Hall, Inc. All rights reserved. 39

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; 49 50 Outline // indicates successful termination } // 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 2003 Prentice Hall, Inc. All rights reserved. 40

1 2 3 // Fig. 7. 20: fig 07_20. cpp (ANOTHER METHOD) // This

1 2 3 // Fig. 7. 20: fig 07_20. cpp (ANOTHER METHOD) // 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 data[ array. Size ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; int insert; // 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 ) << data[ i ]; Outline 23 2003 Prentice Hall, Inc. All rights reserved. 41

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 // loop over the element of the array for ( int next = 1; next < array. Size; next++ ) { insert = data[ next ]; // store the value in the current element int move. Item = next; // initialize location to place element Outline // search for the location in which to put the current element while (( move. Item > 0 ) && (data[move. Item - 1 ] > insert ) { // shift element one slot to the right data [move. Item] = data[move. Item - 1]; move. Item-} data [move. Item] = insert; } // end for 2003 Prentice Hall, Inc. All rights reserved. 42

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 i = 0; i < array. Size; i++ ) cout << setw( 4 ) << data[ i ]; 45 46 cout << endl; 47 48 return 0; 49 50 Outline // indicates successful termination } // 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 2003 Prentice Hall, Inc. All rights reserved. 43

// Recursive solution for linear int linear. Search. Recursive( const int main() { const

// Recursive solution for linear int linear. Search. Recursive( const int main() { const int array. Size = 100; int a[ array. Size ]; int search. Key; search int [], int ); // size of array a // create array a // value to locate in a for ( int i = 0; i < array. Size; i++ ) // create some data a[ i ] = 2 * i; cout << "Enter integer search key: "; cin >> search. Key; int element = linear. Search. Recursive( a, search. Key, 0, array. Size - 1); // display results if ( element != -1 ) cout << "Found value in element " << element << endl; else cout << "Value not found" << endl; return 0; // indicates successful termination } // Recursive function for array search int linear. Search. Recursive( const int array[], int key, int low, int high ) { if (array[low] == key) return low; else if (low == high) return -1; else return linear. Search. Recursive(array , key, low + 1, high); } 2003 Prentice Hall, Inc. All rights reserved. 44