820 likes | 837 Vues
Chapter 4 - Arrays. Outline 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using Arrays 4.8 Searching Arrays: Linear Search and Binary Search
E N D
Chapter 4 - Arrays Outline 4.1 Introduction4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using Arrays 4.8 Searching Arrays: Linear Search and Binary Search 4.9 Multiple-Subscripted Arrays
4.1 Introduction • An Array is a group of consecutive memory locations that all share the same name and the same data type • Arrays are structures of related data items • Arrays are Static entities (same size throughout program) Simple variable: sum 35.05 Array: c 87.4 77.3 - 52.9 100.1 32.4 • We have two types of arrays • One-dimensional array • Multidimensional arrays
Name of array is c (Note that all elements of this array have the same name) c[0] -45 c[1] 6 c[2] 0 c[3] 72 c[4] 1543 c[5] -89 c[6] 0 c[7] 62 c[8] -3 c[9] 1 c[10] 6453 c[11] 78 Position number of the element within array c 4.2 Arrays
4.2 Arrays • Arrays • Arrays are consecutive groups of memory locations • They have same name and data type (int, char, etc.) • Individual members of arrays are called Elements • To refer to an element • We specify the array name followed by position number or subscript or and index in a square brackets ( [] ) • Format: arrayname [position number] • Subscripts are represented by consecutive integers, starting with subscript Zero. Remember first element of an array is always at subscript 0 • The second element of an array c is referred to as c[1] and the nth element of array c is referred to as c[n-1] • Example of N-element array c c [0], c [1], …, c [n - 1] • The nth element is at position n-1
4.2 Arrays • Array elements are treated like any other variable • Assignment and printing for an element of integer array c c[0] = 3; // assigning 3 to element c[0] cout << c[0]; // printing the value of c[0] • A subscripts must be an integer or an integer expression int a = 2, b = 3; c[a + b] += 2; cout << c[b] + c[0] << endl; int abc = c[7] / 9; • We can perform operations inside the subscript c[5 – 2] same as c[3] • Brackets have the same level of precedence as parentheses
4.3 Declaring Arrays • Declarations have the sole purpose of telling the compiler the name and the type of a variable so that memory space can be allocated • When declaring arrays, specify • The name of the array • The type of the array (any data type, int, float, double, char, … etc) • The number of elements (because an array has more than one element sharing the same name) • Example: typearrayName [arraySize]; int c[10]; // “c” is an array of 10 integers float d[3284];// “d” is an array of 3284 floats • We can declare multiple arrays of the same type • Use comma separated list, same as regular variables int b[100], x[27];
4.4 Examples Using Arrays • Initializing arrays • Elements of an array can be initialized by the use of a repetition structure such as a for loop • Inside the for body we set each element • Elements of an array can also be initialized using an initializer list • Specify each element when the array is declared int n[5] = {1, 2, 3, 4, 5}; • If not enough initializers, rightmost elements will be set to 0 • If too many syntax error • To set every element to 0, we set the first element explicitly to 0 and the remaining elements are implicitly initialized to zero int n[5] = {0}; or static int n[5]; • If array size is omitted, initializers will determine the size int n[] = {1, 2, 3, 4, 5}; • 5 initializers, therefore 5 element array
1 // Fig. 4.3: fig04_03.cpp: Initializing an array. 2 #include <iostream.h> 3 #include <iomanip.h> 4 5 int main() { 6 int n[10]; // n is an array of 10 integers 7 8 // initialize elements of array n to 0 9 for (int i = 0; i < 10; i++) 10 n[i] = 0; // set element at location i to 0 11 12 cout << "Element" << setw(13) << "Value" << endl; 13 14 // output contents of array n in tabular format 15 for (int j = 0; j < 10; j++) 16 cout << setw(7) << j << setw(13) << n[j] << endl; 17 18 return0; } // end main Declare a 10-element array of integers. Initialize array to 0 using a for loop. Note that the array has elements from n[0] to n[9]. fig04_03.cpp(1 of 1)fig04_03.cppoutput (1 of 1) Element Value 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0
1 // Fig. 4.4: fig04_04.cpp: Initializing an array with a declaration. 2 #include <iostream.h> 3 #include <iomanip.h> 4 5 int main() 6 { 7 // use initializer list to initialize array n 8 int n[10] = {32, 27, 64, 18, 95, 14, 90, 70, 60, 37}; 9 10 cout << "Element" << setw(13) << "Value" << endl; 11 12 // output contents of array n in tabular format 13 for (int i = 0; i < 10; i++) 14 cout << setw(7) << i << setw(13) << n[i] << endl; 15 16 return0; // indicates successful termination 17 } // end main Note the use of the initializer list. fig04_04.cpp(1 of 1)fig04_04.cppoutput (1 of 1) Element Value 0 32 1 27 2 64 3 18 4 95 5 14 6 90 7 70 8 60 9 37
4.4 Examples Using Arrays • Array size • Can be specified with constant variable (const) • const int arraySize = 20; • Constants cannot be changed, keep the same value throughout the program • Constants must be initialized when declared • Constants are also called named read-only variables
1 // Fig. 4.6: fig04_06.cpp 2 // Using a properly initialized constant variable. 3 #include <iostream.h> 4 5 int main() 6 { 7 const intx = 7; // initialized constant variable 8 9 cout << "The value of constant variable x is: " << x << endl; 10 11 return0; // indicates successful termination 12 } // end main Proper initialization of const variable. fig04_06.cpp(1 of 1)fig04_06.cppoutput (1 of 1) The value of constant variable x is: 7
1 // Fig. 4.7: fig04_07.cpp 2 // A const object must be initialized. 3 4 int main() 5 { 6 const int x; // Error: x must be initialized 7 8 x = 7; // Error: cannot modify a const variable 9 10 return0; // indicates successful termination 11 12 } // end main Uninitialized const results in a syntax error. Attempting to modify the const is another error. fig04_07.cpp(1 of 1)fig04_07.cppoutput (1 of 1) d:\cpphtp4_examples\ch04\Fig04_07.cpp(6) : error C2734: 'x' : const object must be initialized if not extern d:\cpphtp4_examples\ch04\Fig04_07.cpp(8) : error C2166: l-value specifies const object
1 // Fig. 4.5: fig04_05.cpp 2 // Initialize array "s" to the even integers from 2 to 20. 3 #include <iostream.h> 4 #include <iomanip.h> 5 6 int main() 7 { 8 // constant variable can be used to specify array size 9 const intarraySize = 10; 10 11 ints[arraySize]; // array s has 10 elements 12 13 for (int i = 0; i < arraySize; i++) // set the values 14 s[i] = 2 + 2 * i; 15 16 cout << "Element" << setw(13) << "Value" << endl; 17 18 // output contents of array s in tabular format 19 for (int j = 0; j < arraySize; j++) 20 cout << setw(7) << j << setw(13) << s[j] << endl; 21 22 return0; // indicates successful termination 23 } // end main Note the use of const keyword. Only const variables can specify array sizes. The program becomes more scalable when we set the array size using a const variable. We can change arraySize, and all the loops will still work (otherwise, we’d have to update every loop in the program). fig04_05.cpp(1 of 1)
Element Value 0 2 1 4 2 6 3 8 4 10 5 12 6 14 7 16 8 18 9 20 fig04_05.cppoutput (1 of 1)
1 // Fig. 4.8: fig04_08.cpp 2 // Compute the sum of the elements of the array. 3 #include <iostream.h> 4 5 int main() 6 { 7 const intarraySize = 10; 8 9 inta[arraySize] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 10 11 int total = 0; 12 13 // sum contents of array a 14 for (int i = 0; i < arraySize; i++) 15 total = total + a[i]; 16 17 cout << "Total of array element values is " << total << endl; 18 19 return0; // indicates successful termination 20 } // end main fig04_08.cpp(1 of 1)fig04_08.cppoutput (1 of 1) Total of array element values is 55
1 // Fig. 4.9: fig04_09.cpp: Histogram printing program. 2 #include <iostream.h> 3 #include <iomanip.h> 4 5 int main() 6 { 7 const intarraySize = 10; 8 int n[arraySize] = {19, 3, 15, 7, 11, 9, 13, 5, 17, 1}; 9 10 cout<<"Element"<<setw(13)<<"Value"<<setw(17)<<"Histogram"<<endl; 11 12 // for each element of array n, output a bar in histogram 13 for (int i = 0; i < arraySize; i++) { 14 cout << setw(7) << i << setw(13) << n[i] << setw (9); 15 16 for (int j = 0; j < n[i]; j++) // print one bar 17 cout << '*'; 18 19 cout << endl; // start next line of output 20 } // end outer for structure 21 22 return0; // indicates successful termination 23 } // end main Prints asterisks corresponding to value inside array element, n[i]. fig04_09.cpp(1 of 1)
Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 * fig04_09.cppoutput (1 of 1)
1 // Fig. 4.10: fig04_10.cpp: Roll a six-sided die 6000 times. 2 #include <iostream.h> 3 #include <iomanip.h> 4 #include <stdlib.h> 5 #include <time.h> 6 7 int main() { 8 const intarraySize = 7; 9 int frequency[arraySize] = {0}; 10 11 srand(time(0)); // seed random-number generator 12 13 for (int roll = 1; roll <= 6000; roll++) // roll die 6000 times 14 ++frequency[1 + rand() % 6];//replaces 20-line switch of Fig. 3.8 15 16 cout << "Face" << setw(13) << "Frequency" << endl; 17 18 // output frequency elements 1-6 in tabular format 19 for (int face = 1; face < arraySize; face++) 20 cout << setw(4) << face << setw(13) << frequency[face] << endl; 21 22 return0;} // end main Remake of old program to roll dice. An array is used instead of 6 regular variables, and the proper element can be updated easily (without needing a switch). This creates a number between 1 and 6, which determines the index of frequency[] that should be incremented. fig04_10.cpp(1 of 1)fig04_10.cppoutput (1 of 1) Face Frequency 1 1003 2 1004 3 999 4 980 5 1013 6 1001
4.4 Examples Using Arrays • Forty students were asked to rate the quality of the food in the student’s cafeteria on a scale of 1 (awful) to 10 (excellent). Put the 40 responses in an integer array and summarize the result of the pool
1 // Fig. 4.11: fig04_11.cpp: Student poll program. 2 #include <iostream.h> 3 #include <iomanip.h> 4 5 int main() { 6 // define array sizes 7 const intresponseSize = 40; // size of array responses 8 const intfrequencySize = 11; // size of array frequency 9 10 // place survey responses in array responses 11 int responses[responseSize] = {1, 2, 6, 4, 8, 5, 9, 7, 8, 12 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 13 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10}; 14 15 // initialize frequency counters to 0 16 int frequency[frequencySize] = {0}; 17 18 // for each answer, select value of an element of array responses 19 // and use that value as subscript in array frequency to determine 20 // element to increment 21 for (int answer = 0; answer < responseSize; answer++) 22 ++frequency[ responses[answer] ]; 23 24 cout<< "Rating" <<setw(17)<< "Frequency" <<endl; // display results 25 26 // output frequencies in tabular format 27 for (int rating = 1; rating < frequencySize; rating++) 28 cout <<setw(6)<< rating <<setw(17)<< frequency[rating] <<endl; 29 return0; } // end main responses[answer] is the rating (from 1 to 10). This determines the index in frequency[] to increment. fig04_11.cpp(1 of 1)
Rating Frequency 1 2 2 2 3 2 4 2 5 5 6 11 7 5 8 7 9 1 10 3 fig04_11.cppoutput (1 of 1)
4.4 Examples Using Arrays • Strings (more in Chapter 5) • Arrays can hold any data type supported by C++, so character data can also be stored in an array. Thus by grouping character data in an array we can form a character string. A string like “hello” is really an array of characters • Note: all strings (arrays of characters) end with null ('\0') • Examples • char string1[] = "hello"; • The Null character is implicitly added, so “string1“ has 6 elements • The character constant representation of the null terminator is ‘\0’ • All strings end with the null terminator character ‘\0’ • Each element of the array will hold one character from the string • The size of the array is determined by the compiler based on the number of characters in the string • char string1[] = {'h','e','l','l','o','\0'}; • Subscripting is the same, we can access individual character directly • cout<<string1[0] is 'h' and cout<<string1[2] is 'l'
4.4 Examples Using Arrays • A character array representing a string should always be declared large enough to hold the characters of the string plus the terminating null character • If we consider the following declaration: • char string2[20]; • Then “string2” is capable of holding a string of 19 characters and a terminating null character
4.4 Examples Using Arrays • Input from keyboard char string2[10]; cin >> string2; • Puts the user input in the array of character string2 • cin reads characters from the keyboard until the first white-space is encountered • The C++ compiler will always add a null character at the end • If too much text is entered, then data is written beyond array • We want to avoid this (section 5.12 explains how) • Printing strings • cout << string2 << endl; • Does not work for other array types (only for character array) • Characters are printed until null is found, null is not printed
1 // Fig. 4_12: fig04_12.cpp: Treating character arrays as strings. 2 #include <iostream.h> 3 4 int main() 5 { 6 char string1[20], // reserves 20 characters 7 char string2[] = "string literal"; // reserves 15 characters 8 9 // read string from user into array string1 10 cout << "Enter the string \"hello there\": "; 11 cin >> string1; // reads "hello" [space terminates input] 12 13 // output strings 14 cout << "string1 is: " << string1 << "\n string2 is: " << string2; 15 16 cout << "\n string1 with spaces between characters is:\n"; 17 18 // output characters until null character is reached 19 for (int i = 0; string1[i] != '\0'; i++) 20 cout << string1[i] << ' '; 21 22 cin >> string1; // reads "there" 23 cout << "\n string1 is: " << string1 << endl; 24 25 return0; // indicates successful termination 26 } // end main Can access the characters in a string using array notation. The loop ends when the null character is found. Two different ways of declaring strings. string2 is initialized, and its size determined automatically. Examples of reading strings from the keyboard and printing them out. fig04_12.cpp(1 of 1)
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 fig04_12.cppoutput (1 of 1)
4.4 Examples Using Arrays • Recall static storage (from Chapter 3) • If static, local variables save values between function calls • A static local variable in a function definition exists for the duration of the program, but it is only visible in the function body • We can declare local arrays to be static • If a static array is not explicitly initialized by the programmer, then it is initialized to zero by the compiler when the array is created static int array[3]; • If the array is not declared as static • Then the array is created and destroyed in every function call
1 // Fig. 4.13: fig04_13.cpp 2 // Static arrays are initialized to zero. 3 #include <iostream.h> 4 5 void staticArrayInit(void); // function prototype 6 void automaticArrayInit(void); // function prototype 7 8 int main() 9 { 10 cout << "First call to each function: \n"; 11 staticArrayInit(); 12 automaticArrayInit(); 13 14 cout << "\n\n Second call to each function: \n"; 15 staticArrayInit(); 16 automaticArrayInit(); 17 18 cout << endl; 19 20 return0; // indicates successful termination 21 } // end main 22 fig04_13.cpp(1 of 3)
23 // function to demonstrate a static local array 24 void staticArrayInit(void) 25 { 26 // initializes the elements to 0 first time the function is called 27 static int array1[3]; 28 29 cout << "\n Values on entering staticArrayInit:\n"; 30 31 // output the contents of array1 32 for (int i = 0; i < 3; i++) 33 cout << "array1[" << i << "] = " << array1[i] << " "; 34 35 cout << "\n Values on exiting staticArrayInit:\n"; 36 37 // modify and output the contents of array1 38 for (int j = 0; j < 3; j++) 39 cout << "array1[" << j << "] = " << (array1[j] += 5) << " "; 40 41 } // end function staticArrayInit 42 Static array, initialized to zero on first function call. Array data is changed; the modified values stay. fig04_13.cpp(2 of 3)
43 // function to demonstrate an automatic local array 44 void automaticArrayInit(void) 45 { 46 // initializes the elements each time the function is called 47 int array2[3] = {1, 2, 3}; 48 49 cout << "\n\n Values on entering automaticArrayInit:\n"; 50 51 // output contents of array2 52 for (int i = 0; i < 3; i++) 53 cout << "array2[" << i << "] = " << array2[i] << " "; 54 55 cout << "\n Values on exiting automaticArrayInit:\n"; 56 57 // modify and output the contents of array2 58 for (int j = 0; j < 3; j++) 59 cout << "array2[" << j << "] = " << (array2[j] += 5) << " "; 60 61 } // 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. fig04_13.cpp(3 of 3)
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 fig04_13.cppoutput (1 of 1)
4.5 Passing Arrays to Functions • To pass an array argument to a function, simply specify the name of the array without any brackets • To pass the array "myArray" to function "myFunction" int myArray[24]; … myFunction(myArray, 24); Or const int arraySize = 24; int myArray[arraySize]; … myFunction(myArray, arraySize); • When passing an array to a function, the array size is normally passed as well (but it is not required). If not passed, then the size knowledge would need to be build into the function itself • Passing the array size is useful for iterating over all the elements of the array
4.5 Passing Arrays to Functions • C++ automatically passes arrays to functions using a simulated call-by-reference instead of call-by-value • Therefore, the called functions can modify the element values in the caller’s original array • the value of the name of the array is the address of the first element of the array • Because the starting address of the array is passed, the called function knows precisely where the array is stored • Therefore, when the called function modifies array elements in its body, then it is modifying the actual elements of the array in their original memory locations • It makes sense performance-wise; if arrays were passed by using a call-by-value, then a copy of each element would be passed
4.5 Passing Arrays to Functions • Individual array elements are passed-by-value, but they can be passed-by-reference • They are like regular variables int One_Element(int, int &); // Function prototype main() { … One_Element(a[5], a[11]); // function call … } // function definition int One_Element(int elm1, int &elem2) { … elm2 += elm1; … }
4.5 Passing Arrays to Functions • For a function to receive an array through a function call, the function’s parameter list must specify that an array will be received (in both the function prototype and function definition) • The function prototype must be written as: void modifyArray(int b[], int arraySize);or void modifyArray(int [], int);//Names are optional in prototype • Both take an array of integers and a single integer • The function definition must be written as: void modifyArray(int b[], int arraySize) • The size of the array is not required between the array brackets • If it is included, then the compiler will ignore it
1 // Fig. 4.14: fig04_14.cpp 2 // Passing arrays and individual array elements to functions. 3 #include <iostream.h> 4 #include <iomanip.h> 5 6 void modifyArray(int [], int); // appears strange 7 void modifyElement(int); 8 9 int main() 10 { 11 const intarraySize = 5; // size of array a 12 inta[arraySize] = {0, 1, 2, 3, 4}; // initialize a 13 14 cout << "Effects of passing entire array by reference:" 15 << "\n\n The values of the original array are: \n"; 16 17 // output original array 18 for (int i = 0; i < arraySize; i++) 19 cout << setw(3) << a[i]; Syntax for accepting an array in parameter list. fig04_14.cpp(1 of 3)
20 21 cout << endl; 22 23 // pass array "a" to modifyArray function by reference 24 modifyArray(a, arraySize); 25 26 cout << "The values of the modified array are: \n"; 27 28 // output the modified array 29 for (int j = 0; j < arraySize; j++) 30 cout << setw(3) << a[j]; 31 32 // output the value of element a[ 3 ] 33 cout << "\n\n\n" 34 << "Effects of passing array element by value:" 35 << "\n\n The value of a[3] is " << a[3] << '\n'; 36 37 // pass the array element a[ 3 ] by value 38 modifyElement(a[3]); 39 40 // output the value of element a[ 3 ] 41 cout << "The value of a[3] is " << a[3] << endl; 42 43 return0; // indicates successful termination 44 } // end main Pass array name "a" and size to function “modifyArray”. Arrays are passed-by-reference. Pass a single array element by value; the original cannot be modified. fig04_14.cpp(2 of 3)
45 46 // in function modifyArray, array "b" points to 47 // the original array "a" in memory 48 void modifyArray(int b[], int sizeOfArray) 49 { 50 // multiply each array element by 2 51 for (int k = 0; k < sizeOfArray; k++) 52 b[k] *= 2; 53 } // end function modifyArray 54 55 56 // in function modifyElement, integer "e" is a local copy of 57 // array element a[ 3 ] passed from main 58 void modifyElement(int e) 59 { 60 // multiply parameter by 2 61 cout << "Value in modifyElement is " 62 << (e *= 2) << endl; 63 } // end function modifyElement Although named "b", the array points to the original array "a". Thus, it can modify a’s data. Individual array elements are passed by value, and the originals cannot be changed. fig04_14.cpp(3 of 3)
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 fig04_14.cppoutput (1 of 1)
4.5 Passing Arrays to Functions • Since arrays are passed to functions by using simulated call-by-reference, any alteration applied to the array elements in the function’s body willaffect the original array • C++ provides the type qualifier "const" that can be used to prevent any modification of the array values in the function body • void doNotModify(const int []); • When a function specifies an array parameter that is preceded by the "const" qualifier, the elements of the array become constant in the function body, and any attempt to modify an element of the array in the function body results in a syntax error (compiler error)
1 // Fig. 4.15: fig04_15.cpp: Demonstrating the const type qualifier. 3 #include <iostream.h> 4 8 void tryToModifyArray(const int []); // function prototype 9 10 int main() 11 { 12 int a[] = {10, 20, 30}; 13 14 tryToModifyArray(a); 15 16 cout << a[0] << ' ' << a[1] << ' ' << a[2] << '\n'; 18 return0; // indicates successful termination 20 } // end main 21 22 // In function tryToModifyArray, array "b" cannot be used 23 // to modify the original array "a" in main. 24 void tryToModifyArray(constint b[]) 25 { 26 b[0] /= 2; // error 27 b[1] /= 2; // error 28 b[2] /= 2; // error 30 } // end function tryToModifyArray Array parameter is declared as const. Array cannot be modified, even though it is passed by reference. fig04_15.cpp(1 of 1)fig04_15.cppoutput (1 of 1) d:\cpphtp4_examples\ch04\Fig04_15.cpp(26) : error C2166: l-value specifies const object d:\cpphtp4_examples\ch04\Fig04_15.cpp(27) : error C2166: l-value specifies const object d:\cpphtp4_examples\ch04\Fig04_15.cpp(28) : error C2166: l-value specifies const object
4.6 Sorting Arrays • Sorting data • Sorting is an important computing task • Virtually every organization must sort some data • Massive amounts must be sorted • Bubble sort (sinking sort) • Several passes through the array • Successive pairs of elements are compared • If increasing order (or identical), no change • If decreasing order, elements exchanged • Repeat these steps for every element for each pass
4.6 Sorting Arrays • Example: • Go left to right, and exchange elements as necessary • One pass for each element • Original: 3 5 2 7 1 • Pass 1: 3 2 51 7(elements 2, 5 and 1, 7 are exchanged) • Pass 2: 2 31 5 7 (elements 2, 3 and 1, 5 are exchanged) • Pass 3: 2 1 3 5 7 (elements 1, 3 are exchanged) • Pass 4: 1 2 3 5 7 (elements 1, 2 are exchanged) • Pass 5: 1 2 3 5 7 (no exchange) • Small elements "bubble" to the top (like 1 in this example)
4.6 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 the value of "x" which is 3 x = y; // "x" gets the value of "y" which is 4 y = temp; // "y" gets the value of "temp" which is 3
1 // Fig. 4.16: fig04_16.cpp 2 // This program sorts an array's values into ascending order. 3 #include <iostream.h> 4 #include <iomanip.h> 5 6 int main() 7 { 8 const intarraySize = 10; // size of array a 9 int a[arraySize] = {2, 6, 4, 8, 10, 12, 89, 68, 45, 37}; 10 int hold; // temporary location used to swap array elements 11 12 cout << "Data items in original order \n"; 13 14 // output original array 15 for (int i = 0; i < arraySize; i++) 16 cout << setw(4) << a[i]; 17 fig04_16.cpp(1 of 2)
18 // bubble sort: loop to control the number of passes 19 for (int pass = 0; pass < arraySize - 1; pass++) { 20 21 // loop to control the number of comparisons per pass 22 for (int comp = 0; comp < arraySize - 1; comp++) { 23 24 // compare side-by-side elements and swap them if 25 // first element is greater than second element 26 if ( a[comp] > a[comp + 1] ) { 27 hold = a[comp]; 28 a[comp] = a[comp + 1]; 29 a[comp + 1] = hold; 30 } // end if 31 } // end of inner for loop 32 } // end of outer for loop 33 cout << "\n Data items in ascending order\n"; 34 35 // output sorted array 36 for (int k = 0; k < arraySize; k++) 37 cout << setw(4) << a[k]; 38 39 cout << endl; 40 return0; // indicates successful termination 41 } // end main Pass through the array size-1 times If the element on the left (index comp) is larger than the element on the right (index comp + 1), then we swap them. Remember the need for a temp variable. fig04_16.cpp(2 of 2)fig04_16.cppoutput (1 of 1) 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
4.7 Case Study: Computing Mean, Medianand Mode Using Arrays • Computers are commonly used to compile and analyze the results of surveys and opinion polls. Assume we have an array initialized with 99 responses to a survey, where each of the responses is a number from 1 to 9. Write a program to compute the mean, median, and mode of the 99 values.
4.7 Case Study: Computing Mean, Medianand Mode Using Arrays • Mean • Arithmetic average of the 99 values (sum / number of elements) • Function mean computes the mean by totaling the 99 elements and dividing the result by 99 • Median • Median is the number in middle of the sorted list. • Example: 3, 5, 6, 7, 9 (6 is median) • Thus, function median determines the median by calling function bubbleSort to sort the response array and then it picks the middle element • If we have an even number of elements, take average of middle two
4.7 Case Study: Computing Mean, Medianand Mode Using Arrays • Mode • The mode is the number that occurs most frequently among the 99 responses • Example: 1, 1, 1, 3, 5, 5, 7, 10, 10 (1 is the mode) • Function mode counts the number of responses of each type and then selects the value with the greatest count • Function mode also produces a histogram to aid in determining the mode graphically
1 // Fig. 4.17: fig04_17.cpp: 2 // This program introduces the topic of survey data analysis. 3 // It computes the mean. 4 #include <iostream.h> 5 #include <iomanip.h> 6 7 void mean(constint [], int); 8 9 int main() 10 { 11 const int responseSize = 99; // the size of array responses 12 13 // initialize array responses 14 int response[responseSize] = 15 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9, 16 7, 8, 9, 5, 9, 8, 7, 8, 7, 8, 17 6, 7, 8, 9, 3, 9, 8, 7, 8, 7, 18 7, 8, 9, 8, 9, 8, 9, 7, 8, 9, 19 6, 7, 8, 7, 8, 7, 9, 8, 9, 2, 20 7, 8, 9, 8, 9, 8, 9, 7, 5, 3, 21 5, 6, 7, 2, 5, 3, 9, 4, 6, 4, 22 7, 8, 9, 6, 8, 7, 8, 9, 7, 8, 23 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 24 4, 5, 6, 1, 6, 5, 7, 8, 7 }; 25 26 // process responses 27 mean(response, responseSize); 28 29 return0; // indicates successful termination 30 } // end main fig04_17.cpp(1 of 2)