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

2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

Embed Size (px)

Citation preview

Page 1: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

1

Arrays

OutlineExamples Using ArraysPassing arrays to functionsClass GradeBook: store student gradesSearching Arrays—Linear searchSorting ArraysMidterm Solution

Page 2: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

2

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 string1[] = “first”;– The size of array string1 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 ‘\0’)• A character array representing a string should be

defined large enough to hold the number of characters in the string + the termination character

Page 3: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

3

Using character arrays to store and manipulate strings

• One could also use this method to declare strings:

char string1[] = {‘f’, ‘i’, ‘r’, ‘s’, ‘t’, ‘\0’};

If you don’t use ‘\0’, the array would simply represent an array of characters, not a string!

if you specify the size of string1 and the size of “list of initializers” is larger syntax error

• char arrays can be manipulated as other arrays, example:– string[0] = ‘f’;

Page 4: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

4

Using character arrays to store and manipulate strings

• Input from keyboardchar string2[ 20 ];

cin >> string2;

– Puts user input in string• Stops at first whitespace characterAdds null character

– If too much text entered, data written beyond array

• We want to avoid this

• Printing strings– cout << string2 << endl;

• Does not work for other array types

– Characters printed until null found

Page 5: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline5

1 // Fig. 7.12: fig07_12.cpp2 // treating character arrays as strings.3 #include <iostream>4 using std::cout;5 using std::cin;6 using std::endl;78 int main()9 {10 char string1 [20]; // reserve 20 characters11 char string2 [] = “string literal”; // reserve 15 characters12 13 // read string from user into array string114 cout << “Enter the string “\hello there\”: ”;15 cin >> string1; // read “hello” [space terminates input]1617 // output strings18 cout << “string1 is: ” << string1 << “\nstring2 is: ” << string2; 19 cout << “\nstring1 with spaces between characters is:\n”;2021 // output characters until null character is reached22 for ( int i = 0; string1[ i ]!= ‘\0’; i++ )23 cout << string1[ i ] << ‘ ’;2425 cin >> string1; // reads “there”26 cout << “\nstring1 is: ” << string1 <<endl; 2728 return 0; // indicates successful termination 29 } // end main

Page 6: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline6

Enter the string “hello there”: hello there

string1 is: hello

string2 is: string literal

string1 with spaces between characters is:

h e l l o

string1 is: there

Page 7: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

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 zerostatic int array[3];

• If not static– Created (and destroyed) in every function call

Page 8: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline8

1 // Fig. 7.13: fig07_13.cpp2 // Static arrays are initialized to zero.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 void staticArrayInit( void ); // function prototype9 void automaticArrayInit( void ); // function prototype10 11 int main()12 {13 cout << "First call to each function:\n";14 staticArrayInit();15 automaticArrayInit();16 17 cout << "\n\nSecond call to each function:\n";18 staticArrayInit();19 automaticArrayInit();20 cout << endl;21 22 return 0; // indicates successful termination23 24 } // end main25

Page 9: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline9

26 // function to demonstrate a static local array27 void staticArrayInit( void )28 {29 // initializes elements to 0 first time function is called30 static int array1[ 3 ]; 31 32 cout << "\nValues on entering staticArrayInit:\n";33 34 // output contents of array135 for ( int i = 0; i < 3; i++ )36 cout << "array1[" << i << "] = " << array1[ i ] << " ";37 38 cout << "\nValues on exiting staticArrayInit:\n";39 40 // modify and output contents of array141 for ( int j = 0; j < 3; j++ )42 cout << "array1[" << j << "] = " 43 << ( array1[ j ] += 5 ) << " ";44 45 } // end function staticArrayInit46

Static array, initialized to zero on first function call.

Array data is changed; the modified values stay.

Page 10: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline10

47 // function to demonstrate an automatic local array48 void automaticArrayInit( void )49 {50 // initializes elements each time function is called51 int array2[ 3 ] = { 1, 2, 3 };52 53 cout << "\n\nValues on entering automaticArrayInit:\n";54 55 // output contents of array256 for ( int i = 0; i < 3; i++ )57 cout << "array2[" << i << "] = " << array2[ i ] << " ";58 59 cout << "\nValues on exiting automaticArrayInit:\n";60 61 // modify and output contents of array262 for ( int j = 0; j < 3; j++ )63 cout << "array2[" << j << "] = " 64 << ( array2[ j ] += 5 ) << " ";65 66 } // end function automaticArrayInit

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.

Page 11: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline11

First call to each function:

 

Values on entering staticArrayInit:

array1[0] = 0 array1[1] = 0 array1[2] = 0

Values on exiting staticArrayInit:

array1[0] = 5 array1[1] = 5 array1[2] = 5

 

Values on entering automaticArrayInit:

array2[0] = 1 array2[1] = 2 array2[2] = 3

Values on exiting automaticArrayInit:

array2[0] = 6 array2[1] = 7 array2[2] = 8

 

Second call to each function:

 

Values on entering staticArrayInit:

array1[0] = 5 array1[1] = 5 array1[2] = 5

Values on exiting staticArrayInit:

array1[0] = 10 array1[1] = 10 array1[2] = 10

 

Values on entering automaticArrayInit:

array2[0] = 1 array2[1] = 2 array2[2] = 3

Values on exiting automaticArrayInit:

array2[0] = 6 array2[1] = 7 array2[2] = 8

Page 12: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

12

Passing Arrays to Functions

• Specify name without brackets – To pass array myArray to myFunction

int myArray[ 24 ];

myFunction( myArray, 24 );

– Array size usually passed, but not required• Useful to iterate over all elements

Page 13: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

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( myArray[3] );

Page 14: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

14

Passing Arrays to Functions

• Functions taking arrays– Function prototype

• void modifyArray( int b[], int arraySize );• void modifyArray( 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 doNotModify( const int [] );

Page 15: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline15

1 // Fig. 7.14: fig07_14.cpp2 // Passing arrays and individual array elements to functions.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 void modifyArray( int [], int ); // appears strange13 void modifyElement( int ); 14 15 int main()16 {17 const int arraySize = 5; // size of array a18 int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize a19 20 cout << "Effects of passing entire array by reference:" 21 << "\n\nThe values of the original array are:\n";22 23 // output original array24 for ( int i = 0; i < arraySize; i++ )25 cout << setw( 3 ) << a[ i ];

Syntax for accepting an array in parameter list.

Page 16: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline16

26 27 cout << endl;28 29 // pass array a to modifyArray by reference30 modifyArray( a, arraySize ); 31 32 cout << "The values of the modified array are:\n";33 34 // output modified array35 for ( int j = 0; j < arraySize; j++ )36 cout << setw( 3 ) << a[ j ];37 38 // output value of a[ 3 ]39 cout << "\n\n\n"40 << "Effects of passing array element by value:"41 << "\n\nThe value of a[3] is " << a[ 3 ] << '\n';42 43 // pass array element a[ 3 ] by value44 modifyElement( a[ 3 ] ); 45 46 // output value of a[ 3 ]47 cout << "The value of a[3] is " << a[ 3 ] << endl;48 49 return 0; // indicates successful termination50 51 } // end main

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

Pass a single array element by value; the original cannot be modified.

Page 17: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline17

52 53 // in function modifyArray, "b" points to 54 // the original array "a" in memory 55 void modifyArray( int b[], int sizeOfArray )56 { 57 // multiply each array element by 2 58 for ( int k = 0; k < sizeOfArray; k++ ) 59 b[ k ] *= 2; 60 61 } // end function modifyArray 62 63 // in function modifyElement, "e" is a local copy of64 // array element a[ 3 ] passed from main 65 void modifyElement( int e ) 66 { 67 // multiply parameter by 2 68 cout << "Value in modifyElement is " 69 << ( e *= 2 ) << endl; 70 71 } // end function modifyElement

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.

Page 18: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline18

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 modifyElement is 12

The value of a[3] is 6

Page 19: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline19

1 // Fig. 7.15: fig07_15.cpp2 // Demonstrating the const type qualifier.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 void tryToModifyArray( const int [] ); // function prototype9 10 int main()11 {12 int a[] = { 10, 20, 30 };13 14 tryToModifyArray( a );15 16 cout << a[ 0 ] << ' ' << a[ 1 ] << ' ' << a[ 2 ] << '\n';17 18 return 0; // indicates successful termination19 20 } // end main21

Array parameter declared as const. Array cannot be modified, even though it is passed by reference.

Page 20: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline20

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

d:\cpphtp7_examples\ch07\Fig07_15.cpp(26) : error C2166: l-value specifies const object

d:\cpphtp7_examples\ch07\Fig07_15.cpp(27) : error C2166: l-value specifies const object

d:\cpphtp7_examples\ch07\Fig07_15.cpp(28) : error C2166: l-value specifies const object

Page 21: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline21

1 // GradeBook.h2 // Definition of class GradeBook that uses an array to store test grades3 // Member functions are defined in GradeBook.cpp45 #include <string>6 using std::string;7 // GradeBook Class definition8 Class GradeBook9 {10 public:11 // const. Number of students who took the test12 const static int students = 10;13 // constructor initializes courseName14 GradeBook( string, const int [] ); 15 void setCourseName(string); // Function that sets the course name16 string getCourseName(); // Function that gets the course name17 void displayMessage(); // Function that displays a welcome message18 void processGrades(); // perform various operations on the grades19 int getMinimum(); // find the minimum grade of the test20 int getMaximum(); // find the maximum grade of the test21 double getAverage(); // determine the average grade of the test22 void outputBarChart(); // output bar char for grade distribution23 void outputGrades(); // output the content of the grades array24 private:25 string courseName; // course name of this GradeBook 26 int grades [students]; // array of student grades 27 }; // end class GradeBook

Class GradeBook: store student grades

Defined as public: it is accessible to the user of the class

Page 22: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

221 // GradeBook.cpp2 // Member function definitions for class GradeBook that3 // uses array to store test grades4 #include <iostream>5 using std::cout; 6 using std::cin; 7 using std::endl; 8 using std::fixed;910 #include <iomanip>11 using std::setprecision; 12 using std::setw;1314 #include “GradeBook.h”15 16 // Constructor initializes courseName with string supplied as argument;17 // initializes counter data members to 0;18 GradeBook::GradeBook(string name, cont int gradesArray[] )19 { 20 setCourseName(name); //initialize courseName21 //copy grades from gradeArray to grades data member22 for ( int grade = 0; grade < students; grade ++ ) 23 grades[ grade ] = gradesArray [ grade ];24 } // End constructor25 // function to set the course name26 void GradeBook::setCourseName(string name)27 { 28 courseName = name; //store name in the courseName29 }

Page 23: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

233031 // Function that gets the course name32 String GradeBook::getCourseName()33 { 34 return courseName; // store the object’s course name35 } // end function getCourseName3637 // Function that displays a welcome message38 void GradeBook::displayMessage()39 { 40 // call getCourseName to get the courseName41 cout << “Welcome to the grade book for\n"<< getCourseName()<<"!“ 42 <<endl;43 } // end function displayMessage44 // perform various operation on the data45 void GradeBook::processGrades()46 { 47 outputGrades(); // output grades array48 cout << “\nClass Average is "<< setprecision (2) << fixed << 49 getAverageGrade()<< endl; 50 cout << “Lowest Grade is "<< getMinimum() << “\nHighest Grade is "<< 51 getMaximum()<< endl;52 outputBarChart(); // call function to print grade distribution53 } // end function processGrades

Print the contents of grades array

Page 24: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

2454 // find minimum grade55 int GradeBook::getMinimum()56 { 57 int lowGrade = 100 ; //assume lowest grade is 10058 //loop through grades array59 for ( int grade = 0; grade < students; grade ++ ) 60 {61 //if current grade lower than lowGrade, assign it to lowGrade 62 if ( grades[ grade ] < lowGrade )63 lowGrade = grades[ grade ] ;64 }65 return lowGrade;66 } 67 // find maximum grade68 int GradeBook::getMaximum()69 { 70 int highGrade = 0; //assume highest grade is 10071 //loop through grades array72 for ( int grade = 0; grade < students; grade ++ ) 73 {74 //if current grade higher than highGrade, assign it to highGrade 75 if ( grades[ grade ] > highGrade )76 highGrade = grades[ grade ] ;77 }78 return highGrade;79 }

Page 25: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

2580 // find average grade81 double GradeBook::getAverage()82 { 83 int total = 0 ; //initialize total84 //sum grades in array85 for ( int grade = 0; grade < students; grade ++ ) 86 {87 total += grades[ grade ] ;88 }89 return static_cast<double> (total)/student;90 }

Page 26: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

2691 void GradeBook::outputBarChart()92 {93 cout << “Grade Distribution:" << endl; 94 const int frequencySize = 11;95 int frequency[frequencySize] = { 0 };96 97 cout << “Grade Distribution:" << endl; 98 99 // for each grade increment the appropriate frequency100 for ( int grade = 0; grade < students ; grade++ ) 101 frequency [ grades [ grade ] / 10 ]++;102 // for each grade frequency, print bar in chart102 for ( int count = 0; count < frequencySize; count++ ) 103 {104 if (count == 0)

105 cout << “0-9:”;106 else if (count == 10)107 cout << “100:”;108 else

109 cout << count * 10 << “-” << (count * 10) + 9<< “: ”;

110 // print bar of asterisks111 for ( int stars = 0; stars < frequency[ count ]; stars++ )112 cout << '*'; 113 114 cout << endl; // start next line of output115 116 }117 }

Loop over the grades array, increment the counter for grades that fall in the appropriate range

Page 27: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

27118 // output the contents of the grades array119 void GradeBook::outputGrades()120 { 121 cout << “\nThe Grades are:\n\n"; 122 123 //output each student’s grade124 for ( int student = 0; student < students; student ++ ) 125 cout << “Student "<< setw(2)<< student + 1 << “: " << setw(3)126 << grades[student]<<endl; 127 }

Page 28: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

281 // figure07_18.cpp2 // Create GRadeBook object using an array of grades3 #include “GradeBook.h” // include definition of class Analysis45 int main()6 {7 // array of student grades8 int gradesArray[ GradeBook::students ] = 9 {87, 68, 94, 100, 83, 78, 85, 91, 76, 87};10 GradeBook myGradeBook(“MECH215 Introduction to C++ Programming“, gradesArray); 11 myGradeBook.displayMessage(); 12 myGradeBook.processGrades();13 return 0; 14 } // end main

Size of array “students” is a public variable and it is accessed in the main function

Page 29: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

29Welcome to the grade book for

MECH215 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 distribution

0-9:

10-19:

20-29:

30-39:

40-49:

50-59:

60-69: *

70-79: * *

80-89: * * * *

90-99: * *

100: *

Page 30: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

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

Page 31: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

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 2N > # of elements• 30 element array takes at most 5 steps

25 > 30

Page 32: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline32

1 // Fig. 7.19: fig07_19.cpp2 // Linear search of an array.3 #include <iostream>4 5 using std::cout;6 using std::cin;7 using std::endl;8 9 int linearSearch( const int [], int, int ); // prototype10 11 int main()12 {13 const int arraySize = 100; // size of array a14 int a[ arraySize ]; // create array a15 int searchKey; // value to locate in a16 17 for ( int i = 0; i < arraySize; i++ ) // create some data18 a[ i ] = 2 * i;19 20 cout << "Enter integer search key: ";21 cin >> searchKey;22 23 // attempt to locate searchKey in array a 24 int element = linearSearch( a, searchKey, arraySize );25

Takes array, search key, and array size.

Page 33: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline33

26 // display results27 if ( element != -1 )28 cout << "Found value in element " << element << endl;29 else30 cout << "Value not found" << endl;31 32 return 0; // indicates successful termination33 34 } // end main35 36 // compare key to every element of array until location is 37 // found or until end of array is reached; return subscript of 38 // element if key or -1 if key not found 39 int linearSearch( const int array[], int key, int sizeOfArray )40 { 41 for ( int j = 0; j < sizeOfArray; j++ ) 42 43 if ( array[ j ] == key ) // if found, 44 return j; // return location of key 45 46 return -1; // key not found 47 48 } // end function linearSearch

Page 34: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline34

Enter integer search key: 36

Found value in element 18

Enter integer search key: 37

Value not found

Page 35: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

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

Page 36: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

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

Page 37: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

37

Sorting Arrays

• Swapping variablesint 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;

temp = x; // temp gets 3

x = y; // x gets 4

y = temp; // y gets 3

Page 38: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline38

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

Page 39: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline39

2425 // loop to control number of passes 26 for ( i = 0; i < arraySize; i++ ) 27 28 // loop to control number of comparisons per pass 29 for ( int j = i+1; j < arraySize; j++ ) 30 31 // compare side-by-side elements and swap them if32 // first element is greater than second element 33 if ( a[ j ] < a[ i ] ) { 34 hold = a[ j ]; 35 a[ j ] = a[ i ]; 36 a[ i ] = hold; 37 38 } // end if 39

If the element on the left (index j) is smaller than the element on the right (index i), then we swap them. Remember the need of a temp variable.

Page 40: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline40

40 cout << "\nData items in ascending order\n";41 42 // output sorted array43 for ( int k = 0; k < arraySize; k++ )44 cout << setw( 4 ) << a[ k ];45 46 cout << endl;47 48 return 0; // indicates successful termination49 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

Page 41: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline41

1 // Fig. 7.20: fig07_20.cpp (ANOTHER METHOD)2 // This program sorts an array's values into ascending order.3 #include <iostream>4 5 using std::cout;6 using std::endl;7 8 #include <iomanip>9 10 using std::setw;11 12 int main()13 {14 const int arraySize = 10; // size of array a15 int data[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };16 int insert; // temporary location used to swap array elements17 18 cout << "Data items in original order\n";19 20 // output original array21 for ( int i = 0; i < arraySize; i++ )22 cout << setw( 4 ) << data[ i ];23

Page 42: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline42

2425 // loop over the element of the array 26 for ( int next = 1; next < arraySize; next++ ) 27 { 28 insert = data[ next ]; // store the value in the current element29 int moveItem = next; // initialize location to place element30 31 // search for the location in which to put the current element32 while (( moveItem > 0 ) && (data[moveItem - 1 ] > insert ) 33 { 34 // shift element one slot to the right35 data [moveItem] = data[moveItem - 1];36 moveItem--37 } 38 data [moveItem] = insert; 39 } // end for

Page 43: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc.All rights reserved.

Outline43

40 cout << "\nData items in ascending order\n";41 42 // output sorted array43 for ( int i = 0; i < arraySize; i++ )44 cout << setw( 4 ) << data[ i ];45 46 cout << endl;47 48 return 0; // indicates successful termination49 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

Page 44: 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades

2003 Prentice Hall, Inc. All rights reserved.

44// Recursive solution for linear search

int linearSearchRecursive( const int [], int , int , int );

int main()

{

const int arraySize = 100; // size of array a

int a[ arraySize ]; // create array a

int searchKey; // value to locate in a

for ( int i = 0; i < arraySize; i++ ) // create some data

a[ i ] = 2 * i;

cout << "Enter integer search key: ";

cin >> searchKey;

int element = linearSearchRecursive( a, searchKey, 0, arraySize - 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 linearSearchRecursive( const int array[], int key, int low, int high )

{

if (array[low] == key)

return low;

else if (low == high)

return -1;

else

return linearSearchRecursive(array, key, low + 1, high);

}