Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II Multidimensional Arrays a everything about one dimensional arrays applies * a all elements of the same data type a just need additional sets of [ ] a a 3-D array has rows, columns, and rank * Except leaving the size out of the formal parameter Parallel Arrays Used when related data is of different data types. grade % of class A 28 B 40 C 29 D 9 F 14 parallel arrays = two or more arrays in which elements with corresponding indexes are related We WILL do this in the next lab * Parallel Arrays for(row… for(col… { cout << “Enter id#”; cin >> id[row][col]; cout << “Enter grade”; cin >> grade[row][col]; } OR for(row… for(col… { } cout << “Enter id and grade”; cin >> id[row][col] >> grade[row][col]; Sum a Row void main(void) { double nums [3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; double sumRow(double [3] [4]); // prototype cout << “The sum of row 3 is “ << sumRow(nums)<<endl; //function call } Sum a Row double sumRow(double ary[3][4]) { int col; double total=0; for(col = 0; col < 4; col++) ary[ ][col]; total += ary[2][col]; //enter row # -1 return total; } output The sum of row 3 is 42 Sum a Column void main(void) { double nums [3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; double sumCol(double [3] [4]); // prototype cout << “The sum of column 3 is “ << sumCol(nums) << endl; //function call } Sum a Column double sumCol(double ary[3][4]) { int row; double total=0; for(row = 0; row<3; row++) ary[row][ ]; //enter col # -1 total += ary[row][2]; return total; } output The sum of column 3 is 21 Array Review -1 Write a C++ program that adds equivalent elements of the two-dimensional arrays named first and second. Both arrays should have two rows and three columns. For example, element [1][2] of the resulting array should be the sum of first[1][2] and second[1][2]. first 16 18 23 54 91 11 sum second 40 70 100 24 52 77 70 110 70 16 19 59 * Sorting Internal Sorts [for small data sets] bubble (exchange) selection External Sorts [for large data sets] Bubble Sort 21 13 9 25 17 Put smaller first 13 21 9 25 17 Put smaller first 13 9 21 25 17 No change 13 9 21 25 17 Put smaller first Bubble Sort 13 9 21 17 25 Begin again and put smaller first 9 13 21 17 25 No change 9 13 21 17 25 Put smaller first 9 13 17 21 25 A Bubble Sort Function void bubble_sort(int array[ ], int length) { int j, k, flag=1, temp; for(j=1; j<=length && flag; j++) { flag=0; // false for(k=0; k < (length-j); k++) { if (array[k+1] > array[k]) // > low to high { temp=array[k+1]; // swap array[k+1]= array[k]; array[k]=temp; flag=1; // indicates a swap } } } } // has occurred Selection Sort index (k) sm_index 21 13 9 15 17 0 2 swap 21, 9 9 13 21 15 17 1 1 swap 13, 13 9 13 21 15 17 2 3 swap 21, 15 9 13 15 21 17 3 4 swap 21, 17 9 13 15 17 21 Selection Sort void sort(double [5]); void swap(double [5], int, int); // prototypes void main(void) { int index; double my_list[ ] = {21, 13, 9, 15, 17}; cout << "\nThe unsorted array is: \n"; for(index=0; index<5; index++) cout << “ “ << my_list[index] << endl; sort(my_list); // function call cout << "\nThe sorted array is: \n"; for(index=0; index<5; index++) cout << “ “ << my_list[index] << endl; } Selection Sort void sort(double testArray[5]) { int n, k, sm_index, pass=0; double smallest; for(k=0; k<4; k++) // size-1 = number of passes { smallest = testArray[k]; sm_index = k; for(n=k+1; n<5; n++) // size = # elem. to look at if(testArray[n] < smallest) { smallest = testArray[n]; sm_index = n; } swap(testArray, sm_index, k); // call to swap() } } Selection Sort void swap(double testArray[5], int smaller, int position) { // position = current position: k double temp; temp = testArray[position]; testArray[position] = testArray[smaller]; testArray[smaller] = temp; } Linear Search Pseudocode For all the items in the list Compare the item with the desired item If the item was found Return the index value of the current item (the position of the element in the array) End If End For Return -1 because the item was not found The “Classic” Linear Search Function int LinearSearch(int list[], int size, int key) { // or “Sequential search” int i; for (i = 0; i < size; i++) { if (list[i] = = key) return i; // return location of element //this will terminate the loop } return -1; // element not in list } Main for linear search int main() { int LinearSearch(int [], int, int); // prototype const int NUMEL = 10; int nums[NUMEL] = {22,5,67,98,45,32,101,99,73,10}; int item, location; cout << "\nEnter the item you are searching for: "; cin >> item; location = LinearSearch(nums, NUMEL, item); if (location > -1) cout << "The item was found at index location " << location << endl; else cout << "The item was not found in the list\n"; return 0; } Binary Search List must be in sorted order The function looks at the midpoint If the midpoint is the item, return the location Else, determine if the item is less than or greater than the midpoint Eliminate the side where the item cannot be, and declare a new midpoint Go again. (A recursive function) Half the list is eliminated on each pass int BinarySearch(int list[], int size, int key) { int left, right, midpt; // list must be in sorted order left = 0; // left end is the first element right = size - 1; // right is the last element while (left <= right){ midpt = (int) ((left + right) / 2); // why integer division? if (key == list[midpt]) return midpt; // if found, the key will be the midpoint else if (key > list[midpt]) // eliminate the left half left = midpt + 1; else right = midpt - 1; // else - eliminate the right half } // end while return -1;} // the key was never found Main for binary search int main() { int BinarySearch(int [], int, int); // prototype const int NUMEL = 10; int nums[NUMEL] = {5,10,22,32,45,67,73,98,99,101}; int item, location; cout << "\nEnter the item you are searching for: "; cin >> item; location = BinarySearch(nums, NUMEL, item); if (location > -1) cout << "The item was found at index location " << location << endl; else cout << "The item was not found in the list\n"; return 0; } Array Review a is an ordered sequence of data of the same type a can be of any valid data type a can be 1-, 2-, or multi- dimensional a must be declared before used a can be assigned and initialized a element numbering starts at zero Array Review a use for loops to access (nested for multidimentional) a can be passed back and forth between functions when sent to functions the actual values are manipulated - not a copy (passed by reference) a Array Review - 6a There is an array of three students each with four exam scores. Assume the scores are known and are: {77, 68, 86, 73}, {96, 87, 89, 78}, {70, 90, 86, 81}. Create a program which will display the lowest grade, the highest grade and the average of the grades to two decimal places. Array Review - 6b #include <iostream> #include <iomanip.> using namespace std; const int STUDENTS = 3; // global, so main and all const int EXAMS = 4; // functions can access int mini (int [][EXAMS], int, int); int maxi (int [][EXAMS], int, int); float average(int [], int); void printArray(int [][EXAMS], int, int); Array Review - 6c void main(void) { int studentGrades[STUDENTS][EXAMS] = {{77, 68, 86, 73}, {96, 87, 89, 78}, {70, 90, 86, 81}}; cout << "The array is:" << endl; printArray(studentGrades, STUDENTS, EXAMS); cout<<endl<<endl<<"Lowest grade: " << mini (studentGrades, STUDENTS, EXAMS) << endl << "Highest grade: " << maxi (studentGrades, STUDENTS, EXAMS)<<endl; for (int person = 0; person < STUDENTS; person++) cout << "The average grade for student " << person << " is " <<setiosflags(ios::fixed | ios::showpoint)<<setprecision(2) << average(studentGrades[person], EXAMS) << endl; } Array Review - 6d int mini(int grades[][EXAMS], int maxi(int grades[][EXAMS], int pupils, int tests) int pupils, int tests) { { int lowGrade = 100; int highGrade = 0; for (int i = 0; i < pupils; i++) for (int i = 0; i < pupils; i++) for (int j = 0; j < tests; j++) for (int j = 0; j < tests; j++) if (grades[i][j] < if (grades[i][j] > highGrade) lowGrade) highGrade = grades[i][j]; lowGrade = grades[i][j]; return highGrade; return lowGrade; } } Array Review - 6e float average(int setOfGrades[],void printArray(int grades[][EXAMS], int tests) int pupils, int tests) { { int total = 0; cout << " [0] [1] [2] [3]"; for (int i = 0; i < tests; i++) for (int i = 0; i < pupils; i++) { cout << endl<< "studentGrades[" total += setOfGrades[i]; << i << "] "; return (float) total / tests; } for (int j = 0; j < tests; j++) cout << setiosflags(ios::left) << setw(5) << grades[i][j]; } Array Review - 6f function call: average(studentGrades[person], EXAMS) float average(int setOfGrades[], int tests) { int total = 0; for (int i = 0; i < tests; i++) total += setOfGrades[i]; } return total / tests; Common Errors Not declaring the array First element is called zero; last element is one less than the number of elements Out of range subscripts - no warning Error in the for loop - check the counter Not initializing the array Common Errors Aggregate operations not allowed Omitting array size - permitted only when declared as a formal parameter initialized in the declaration If array is /* in */ only, declare the formal parameter as const to prevent accidental modification Debugging array subscripts recheck array size in declaration, initialization, and for loops Prevention - plan first! Valuation tables Display values with cout C++ Debugger End Note I really hate this darn machine, I wish they would sell it. It never does quite what I want, But only what I tell it.