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

Slides:



Advertisements
Similar presentations
Arrays. Introduction Arrays –Structures of related data items –Static entity - same size throughout program A few types –C-like, pointer-based arrays.
Advertisements

4.1Introduction Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based arrays (C-like) –Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Review (Week1) C++_ the unit of programming is the class from which objects are eventually instantiated. C++ classes contain functions that implement class.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring Arrays 6.4Examples Using Arrays 6.5Passing.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
4.1Introduction Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based arrays (C-like) –Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Arrays & Pointers.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
1 Lecture 5: Part 1 Searching Arrays Searching Arrays: Linear Search and Binary Search Search array for a key value Linear search  Compare each.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides:
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Algorithm and Programming Array Dr. Ir. Riri Fitri Sari MM MSc International Class Electrical Engineering Dept University of Indonesia 15 March 2009.
C Lecture Notes 1 Arrays Lecture 6. C Lecture Notes 2 6.1Introduction Arrays –Structures of related data items –Static entity – same size throughout program.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
1 Arrays as Lists with examples. 2 Review Arrays –Structures of related data items of the same type –Data items (called array elements) are stored at.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
1 Lecture 8 Arrays Part II Sorting Arrays Sorting data  Important computing application  Virtually every organization must sort some data Massive.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 13 October 13, 2009.
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing Arrays to Functions 4.6Sorting Arrays 4.7Case.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Vectors.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig04_03.cpp (1 of 2) 1 // Fig. 4.3: fig04_03.cpp 2 // Initializing an array. 3 #include 4 5.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Arrays 3.Declaring Arrays 4.Examples Using Arrays 5.Multidimensional Arrays 6.Multidimensional.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Consecutive group of memory locations –Same name and type To refer to an element, specify.
CSC 113: C OMPUTER P ROGRAMMING (T HEORY = 03, L AB = 01) Computer Science Department Bahria University, Islamabad.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Arrays + Functions Outline 6.5Passing Arrays to Functions.
4.1Introduction Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based arrays (C-like) –Arrays.
Chapter 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays
C++ Programming Lecture 15 Arrays – Part II
آرايه ها اصول كامپيوتر 1.
C++ Programming Lecture 15 Arrays – Part II
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
C Arrays.
Arrays Kingdom of Saudi Arabia
Arrays as Lists with examples.
Arrays Outline Introduction Arrays Declaring Arrays
CISC181 Introduction to Computer Science Dr
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
4.1 Introduction Arrays A few types Structures of related data items
Arrays Kingdom of Saudi Arabia
Chapter 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Chapter 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Chapter 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Capitolo 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Arrays Arrays A few types Structures of related data items
Chapter 3 Arrays Dr. A. PHILIP AROKIADOSS Assistant Professor
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

 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. 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

 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’;

 2003 Prentice Hall, Inc. All rights reserved. 4 Using character arrays to store and manipulate strings Input from keyboard char string2[ 20 ]; cin >> string2; –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 << string2 << endl; Does not work for other array types –Characters printed until null found

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

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

 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 zero static int array[3]; If not static –Created (and destroyed) in every function call

 2003 Prentice Hall, Inc. All rights reserved. Outline 8 1 // Fig. 7.13: fig07_13.cpp 2 // Static arrays are initialized to zero. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 void staticArrayInit( void ); // function prototype 9 void automaticArrayInit( void ); // function prototype int main() 12 { 13 cout << "First call to each function:\n"; 14 staticArrayInit(); 15 automaticArrayInit(); cout << "\n\nSecond call to each function:\n"; 18 staticArrayInit(); 19 automaticArrayInit(); 20 cout << endl; return 0; // indicates successful termination } // end main 25

 2003 Prentice Hall, Inc. All rights reserved. Outline 9 26 // function to demonstrate a static local array 27 void staticArrayInit( void ) 28 { 29 // initializes elements to 0 first time function is called 30 static int array1[ 3 ]; cout << "\nValues on entering staticArrayInit:\n"; // output contents of array1 35 for ( int i = 0; i < 3; i++ ) 36 cout << "array1[" << i << "] = " << array1[ i ] << " "; cout << "\nValues on exiting staticArrayInit:\n"; // modify and output contents of array1 41 for ( int j = 0; j < 3; j++ ) 42 cout << "array1[" << j << "] = " 43 << ( array1[ j ] += 5 ) << " "; } // end function staticArrayInit 46 Static array, initialized to zero on first function call. Array data is changed; the modified values stay.

 2003 Prentice Hall, Inc. All rights reserved. Outline // function to demonstrate an automatic local array 48 void automaticArrayInit( void ) 49 { 50 // initializes elements each time function is called 51 int array2[ 3 ] = { 1, 2, 3 }; cout << "\n\nValues on entering automaticArrayInit:\n"; // output contents of array2 56 for ( int i = 0; i < 3; i++ ) 57 cout << "array2[" << i << "] = " << array2[ i ] << " "; cout << "\nValues on exiting automaticArrayInit:\n"; // modify and output contents of array2 62 for ( int j = 0; j < 3; j++ ) 63 cout << "array2[" << j << "] = " 64 << ( array2[ j ] += 5 ) << " "; } // 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.

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

 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

 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] );

 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 [] );

 2003 Prentice Hall, Inc. All rights reserved. Outline 15 1 // Fig. 7.14: fig07_14.cpp 2 // Passing arrays and individual array elements to functions. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::setw; void modifyArray( int [], int ); // appears strange 13 void modifyElement( int ); int main() 16 { 17 const int arraySize = 5; // size of array a 18 int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize a cout << "Effects of passing entire array by reference:" 21 << "\n\nThe values of the original array are:\n"; // output original array 24 for ( int i = 0; i < arraySize; i++ ) 25 cout << setw( 3 ) << a[ i ]; Syntax for accepting an array in parameter list.

 2003 Prentice Hall, Inc. All rights reserved. Outline cout << endl; // pass array a to modifyArray by reference 30 modifyArray( a, arraySize ); cout << "The values of the modified array are:\n"; // output modified array 35 for ( int j = 0; j < arraySize; j++ ) 36 cout << setw( 3 ) << a[ j ]; // 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'; // pass array element a[ 3 ] by value 44 modifyElement( a[ 3 ] ); // output value of a[ 3 ] 47 cout << "The value of a[3] is " << a[ 3 ] << endl; return 0; // indicates successful termination } // 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.

 2003 Prentice Hall, Inc. All rights reserved. Outline // 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; } // end function modifyArray // in function modifyElement, "e" is a local copy of 64 // 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; } // 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.

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

 2003 Prentice Hall, Inc. All rights reserved. Outline 19 1 // Fig. 7.15: fig07_15.cpp 2 // Demonstrating the const type qualifier. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 void tryToModifyArray( const int [] ); // function prototype 9 10 int main() 11 { 12 int a[] = { 10, 20, 30 }; tryToModifyArray( a ); cout << a[ 0 ] << ' ' << a[ 1 ] << ' ' << a[ 2 ] << '\n'; return 0; // indicates successful termination } // end main 21 Array parameter declared as const. Array cannot be modified, even though it is passed by reference.

 2003 Prentice Hall, Inc. All rights reserved. Outline // In function tryToModifyArray, "b" cannot be used 23 // 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 } // 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

 2003 Prentice Hall, Inc. All rights reserved. Outline 21 1 // GradeBook.h 2 // Definition of class GradeBook that uses an array to store test grades 3 // Member functions are defined in GradeBook.cpp 4 5 #include 6 using std::string; 7 // GradeBook Class definition 8 Class GradeBook 9 { 10 public: 11 // const. Number of students who took the test 12 const static int students = 10; 13 // constructor initializes courseName 14 GradeBook( string, const int [] ); 15 void setCourseName(string); // Function that sets the course name 16 string getCourseName(); // Function that gets the course name 17 void displayMessage(); // Function that displays a welcome message 18 void processGrades(); // perform various operations on the grades 19 int getMinimum(); // find the minimum grade of the test 20 int getMaximum(); // find the maximum grade of the test 21 double getAverage(); // determine the average grade of the test 22 void outputBarChart(); // output bar char for grade distribution 23 void outputGrades(); // output the content of the grades array 24 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

 2003 Prentice Hall, Inc. All rights reserved // GradeBook.cpp 2 // Member function definitions for class GradeBook that 3 // uses array to store test grades 4 #include 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 using std::fixed; 9 10 #include 11 using std::setprecision; 12 using std::setw; #include “GradeBook.h” // 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 courseName 21 //copy grades from gradeArray to grades data member 22 for ( int grade = 0; grade < students; grade ++ ) 23 grades[ grade ] = gradesArray [ grade ]; 24 } // End constructor 25 // function to set the course name 26 void GradeBook::setCourseName(string name) 27 { 28 courseName = name; //store name in the courseName 29 }

 2003 Prentice Hall, Inc. All rights reserved // Function that gets the course name 32 String GradeBook::getCourseName() 33 { 34 return courseName; // store the object’s course name 35 } // end function getCourseName // Function that displays a welcome message 38 void GradeBook::displayMessage() 39 { 40 // call getCourseName to get the courseName 41 cout << “Welcome to the grade book for\n"<< getCourseName()<<"!“ 42 <<endl; 43 } // end function displayMessage 44 // perform various operation on the data 45 void GradeBook::processGrades() 46 { 47 outputGrades(); // output grades array 48 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 distribution 53 } // end function processGrades Print the contents of grades array

 2003 Prentice Hall, Inc. All rights reserved // find minimum grade 55 int GradeBook::getMinimum() 56 { 57 int lowGrade = 100 ; //assume lowest grade is //loop through grades array 59 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 grade 68 int GradeBook::getMaximum() 69 { 70 int highGrade = 0; //assume highest grade is //loop through grades array 72 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 }

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

 2003 Prentice Hall, Inc. All rights reserved void GradeBook::outputBarChart() 92 { 93 cout << “Grade Distribution:" << endl; 94 const int frequencySize = 11; 95 int frequency[frequencySize] = { 0 }; cout << “Grade Distribution:" << endl; // for each grade increment the appropriate frequency 100 for ( int grade = 0; grade < students ; grade++ ) 101 frequency [ grades [ grade ] / 10 ]++; 102 // for each grade frequency, print bar in chart 102 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 asterisks 111 for ( int stars = 0; stars < frequency[ count ]; stars++ ) 112 cout << '*'; cout << endl; // start next line of output } 117 } Loop over the grades array, increment the counter for grades that fall in the appropriate range

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

 2003 Prentice Hall, Inc. All rights reserved // figure07_18.cpp 2 // Create GRadeBook object using an array of grades 3 #include “GradeBook.h” // include definition of class Analysis 4 5 int main() 6 { 7 // array of student grades 8 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

 2003 Prentice Hall, Inc. All rights reserved. 29 Welcome 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 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: *

 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

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

 2003 Prentice Hall, Inc. All rights reserved. Outline 32 1 // Fig. 7.19: fig07_19.cpp 2 // Linear search of an array. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 int linearSearch( const int [], int, int ); // prototype int main() 12 { 13 const int arraySize = 100; // size of array a 14 int a[ arraySize ]; // create array a 15 int searchKey; // value to locate in a for ( int i = 0; i < arraySize; i++ ) // create some data 18 a[ i ] = 2 * i; cout << "Enter integer search key: "; 21 cin >> searchKey; // attempt to locate searchKey in array a 24 int element = linearSearch( a, searchKey, arraySize ); 25 Takes array, search key, and array size.

 2003 Prentice Hall, Inc. All rights reserved. Outline // display results 27 if ( element != -1 ) 28 cout << "Found value in element " << element << endl; 29 else 30 cout << "Value not found" << endl; return 0; // indicates successful termination } // end main // 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++ ) if ( array[ j ] == key ) // if found, 44 return j; // return location of key return -1; // key not found } // end function linearSearch

 2003 Prentice Hall, Inc. All rights reserved. Outline 34 Enter integer search key: 36 Found value in element 18 Enter integer search key: 37 Value not found

 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

 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: –Pass 1: (elements exchanged) –Pass 2: –Pass 3: (no changes needed) –Pass 4: –Pass 5:

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

 2003 Prentice Hall, Inc. All rights reserved. Outline 38 1 // Fig. 7.20: fig07_20.cpp 2 // This program sorts an array's values into ascending order. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::setw; int main() 13 { 14 const int arraySize = 10; // size of array a 15 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 16 int hold; // temporary location used to swap array elements cout << "Data items in original order\n"; // output original array 21 for ( int i = 0; i < arraySize; i++ ) 22 cout << setw( 4 ) << a[ i ]; 23

 2003 Prentice Hall, Inc. All rights reserved. Outline // loop to control number of passes 26 for ( i = 0; i < arraySize; i++ ) // loop to control number of comparisons per pass 29 for ( int j = i+1; j < arraySize; j++ ) // compare side-by-side elements and swap them if 32 // 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; } // 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.

 2003 Prentice Hall, Inc. All rights reserved. Outline cout << "\nData items in ascending order\n"; // output sorted array 43 for ( int k = 0; k < arraySize; k++ ) 44 cout << setw( 4 ) << a[ k ]; cout << endl; return 0; // indicates successful termination } // end main Data items in original order Data items in ascending order

 2003 Prentice Hall, Inc. All rights reserved. Outline 41 1 // Fig. 7.20: fig07_20.cpp (ANOTHER METHOD) 2 // This program sorts an array's values into ascending order. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::setw; int main() 13 { 14 const int arraySize = 10; // size of array a 15 int data[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 16 int insert; // temporary location used to swap array elements cout << "Data items in original order\n"; // output original array 21 for ( int i = 0; i < arraySize; i++ ) 22 cout << setw( 4 ) << data[ i ]; 23

 2003 Prentice Hall, Inc. All rights reserved. Outline // 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 element 29 int moveItem = next; // initialize location to place element // search for the location in which to put the current element 32 while (( moveItem > 0 ) && (data[moveItem - 1 ] > insert ) 33 { 34 // shift element one slot to the right 35 data [moveItem] = data[moveItem - 1]; 36 moveItem-- 37 } 38 data [moveItem] = insert; 39 } // end for

 2003 Prentice Hall, Inc. All rights reserved. Outline cout << "\nData items in ascending order\n"; // output sorted array 43 for ( int i = 0; i < arraySize; i++ ) 44 cout << setw( 4 ) << data[ i ]; cout << endl; return 0; // indicates successful termination } // end main Data items in original order Data items in ascending order

 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); }