Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 10 ARRAYS II Applications and Extensions.

Similar presentations


Presentation on theme: "CHAPTER 10 ARRAYS II Applications and Extensions."— Presentation transcript:

1 CHAPTER 10 ARRAYS II Applications and Extensions

2 In this chapter, you will:  Learn how to implement the sequential search algorithm  Explore how to sort an array using the selection sort algorithm  Learn how to implement the binary search algorithm  Discover how to manipulate data in a two-dimensional array  Learn about multidimensional arrays

3 LIST PROCESSING  A list is defined as a set of values of the same type.  Some of the basic operations that are performed on a list are: 1. Search the list for a given item. 2. Sort the list. 3. Insert an item in the list. 4. Delete an item from the list.

4 Searching  To search the list, you need three pieces of information: 1. The list, that is, the array containing the list. 2. The length of the list. 3. The item for which you are searching.  After the search is completed, 4. If the item is found, then report “success” and the location where the item was found. 5. If the item is not found, then report “failure.”  To accommodate 4 and 5, we will write a value-returning function.  If the search item is found in the list, the function returns the location in the list where the search item is found; otherwise, it returns –1.

5  The value-returning function has three parameters: 1. The array, list, containing the list. 2. The length of the list, listLength. 3. The item, searchItem, for which you are searching.

6 Sequential Search  Suppose that you want to determine whether 27 is in the list.  First, you compare 27 with list[0] —that is, compare 27 with 35.  As list[0]  27, you then compare 27 with list[1].  As list[1]  27, you compare 27 with the next element in the list—that is, compare 27 with list[2].  Because list[2] = 27, the search stops. This is a successful search.

7  Search for 10.  The search starts with the first element in the list—that is, at list[0].  This time the search item, which is 10, is compared with every item in the list.  This is an unsuccessful search.

8 found is set to false; for(loc = 0; loc < length; loc++) if(list[loc] is equal to searchItem) { found is set to true exit loop } if(found) return loc; else return –1;

9 int seqSearch(const int list[], int listLength, int searchItem) { int loc; bool found = false; for(loc = 0; loc < listLength; loc++) if(list[loc] == searchItem) { found = true; break; } if(found) return loc; else return -1; }

10  If the function seqSearch returns a value greater than or equal to 0, it is a successful search; otherwise, it is an unsuccessful search.

11  Suppose that you have a list with 1000 elements.  If the search item is the second item in the list, the sequential search makes 2 key (also called item) comparisons to determine whether the search item is in the list.  If the search item is the 900th item in the list, the sequential search makes 900 key comparisons to determine whether the search item is in the list.  If the search item is not in the list, the sequential search makes 1000 key comparisons.

12  A sequential search is not very efficient for large lists.  On average, the number of comparisons (key comparisons—not index comparisons) made by the sequential search is equal to half the size of the list.  For a list size of 1000, on average, the sequential search makes about 500 key comparisons.  The preceding search algorithm does not assume that the list is sorted.  If the list is sorted, then you can somewhat improve the search algorithm.

13 Sorting a List: Selection Sort This algorithm finds the location of the smallest element in the unsorted portion of the list, and moves it to the top of the unsorted portion of the list. The first time we locate the smallest item in the entire list, the second time we locate the smallest item in the list starting from the second element in the list, and so on.

14 Suppose that you have the following list. Find the smallest item in the list, which is at position 7. Because this is the smallest item, it must be moved to position 0

15 List after swapping Now the unsorted list is list[1]...list[9].

16 Swap list[3] with list[1] Find the smallest element in the unsorted portion of the list.

17 The process is repeated on list[2]...list[9] After swapping list[1] with list[3], the resulting list is

18  In the unsorted portion of the list: a. Find the location of the smallest element. b. Move the smallest element to the beginning of the unsorted list. for(index = 0; index < length – 1; index++) { a. Find the location, smallestIndex, of the smallest element in list[index]...list[length]. b. Swap the smallest element with list[index]. That is, swap list[smallestIndex] with list[index]. }

19 Step a: smallestIndex = index; //assume first element is the //smallest for(minIndex = index + 1; minIndex < length; minIndex++) if(list[minIndex] < list[smallestIndex]) smallestIndex = minIndex; //current element in //the list is smaller than //the smallest so far, so //update smallestIndex Step b: temp = list[smallestIndex]; list[smallestIndex] = list[index]; list[index] = temp;

20 Before writing the selection sort function, let us apply the above algorithm to sort the following list. The length of list is 6

21 Iteration 1: Sort list[0]...list[5]. Step a: Find the index of the smallest element in list[0]...list[5]. Step b: Swap list[smallestIndex] with list[index], that is, list[3] with list[0]. The resulting array is:

22 Iteration 2: Sort list[1]...list[5]. Here index = 1. Step a: Find the index of the smallest element in list[1]...list[5]. Step b: Swap list[smallestIndex] with list[index]. That is, swap list[1] with list[1].

23 Iteration 3: Sort list[2]...list[5]. Step a: Find the index of the smallest element in list[2]...list[5]. Step b: Swap list[smallestIndex] with list[index]. That is, swap list[4] with list[2].

24 Iteration 4: Sort list[3]...list[5]. Step a: Find the index of the smallest element in list[3]...list[5]. Step b: Swap list[smallestIndex] with list[index]. That is, swap list[3] with list[3].

25 Iteration 5: Sort list[4]...list[5]. Step a: Find the index of the smallest element in list[4]...list[5]. Step b: Swap list[smallestIndex] with list[index]. That is, swap list[5] with list[4].

26 void selectionSort(int list[], int length) { int index; int smallestIndex; int minIndex; int temp; for(index = 0; index < length – 1; index++) { //Step a smallestIndex = index; for(minIndex = index + 1; minIndex < length; minIndex++) if(list[minIndex] < list[smallestIndex]) smallestIndex = minIndex; //Step b temp = list[smallestIndex]; list[smallestIndex] = list[index]; list[index] = temp; }

27 S equential search on a sorted list found is set to false; for(loc = 0; loc < listLength; loc++) if (list[loc] is greater than or equal to searchItem) { found is set to true exit loop } if(found) if(list[loc] == searchItem) return loc; else return –1; else return –1;

28 int seqOrderdSearch(const int list[], int listLength, int searchItem) { int loc;//Line 1 bool found = false;//Line 2 for(loc = 0; loc < listLength; loc++)//Line 3 if(list[loc] >= searchItem)//Line 4 { found = true;//Line 5 break;//Line 6 } if(found)//Line 7 if(list[loc] == searchItem)//Line 8 return loc;//Line 9 else//Line 10 return –1;//Line 11 else//Line 12 return –1;//Line 13 }

29 length = 8 ; searchItem = 35 ; loc = 0, found = false. Iteration locfoundlist[loc]list[loc]>= searchItem 1 0false44 >= 35 is false; loc = 1 2 1false1818 >= 35 is false;loc = 2 3 2false2929 >= 35 is false;loc = 3 4 3false3535 >= 35 is true; found = true

30  found is true, the if statement at Line 8 executes.  list[loc] = 35 and searchItem = 35, the expression list[loc] == searchItem evaluates to true and the return statement at Line 9 returns the value of loc, which is 3.  This is a successful search.

31 searchItem = 40 ; loc = 0 ; found = false. Iteration locfound list[loc] list[loc]>= searchItem 1 0false44 >= 40 is false; loc = 1 2 1false1818 >= 40 is false; loc = 2 3 2false2929 >= 40 is false; loc = 3 4 3false3535 >= 40 is false; loc = 4 5 4false4444 >= 40 is true; found = true

32  found is true. The if statement at Line 8 executes.  list[loc] = 44 and searchItem = 40. The expression list[loc] == searchItem evaluates to false, the statement at Line 9 is skipped, and the return statement at Line 11 executes, which returns –1.  This is an unsuccessful search.

33 Binary Search  A binary search is similar to a dictionary search.  A binary search uses the “divide and conquer” technique to search the list.  First, the search item is compared with the middle element of the list.  If the search item is less than the middle element of the list, we restrict the search to the upper half of the list; otherwise, we search the lower half of the list. Consider the following sorted list of length = 12

34 Determine whether 75 is in the list Compare 75 with the middle element in the list, list[5] (which is 39 ). Because 75  list[5] and 75 > list[5], we then restrict our search to the list list[6]...list[11]

35 int binarySearch(const int list[], int listLength, int searchItem) { int first = 0; int last = listLength - 1; int mid; bool found = false; while(first <= last && !found) { mid = (first + last) / 2; if(list[mid] == searchItem) found = true; else if(list[mid] > searchItem) last = mid - 1; else first = mid + 1; }

36 if(found) return mid; else return –1; }//end binarySearch

37 searchItem = 89 ; first = 0, last = 11, and found = false Iteration firstlastmidlist[mid] Number of Key Comp. 1 011539 2 2 611866 2 3 9111089 1 ( found is true ) searchItem = 34 ; first = 0, last = 11, and found = false Iteration firstlastmidlist[mid] Number of Key Comp. 1 0115392 2 042192 3 343252 4 44434 1 ( found is true )

38 searchItem = 22 ; first = 0, last = 11, and found = false Iteration firstlastmidlist[mid] Number of Key Comp. 1 011539 2 2 04219 2 3 34325 2 4 32 The loop stops (because first > last ) unsuccessful search

39 Performance of Binary Search Suppose that L is a sorted list of 1000 elements Determine whether x is in L.

40 Suppose that x  L[499]. If x < L[499], the next iteration of the while loop looks for x in L[0]...L[498] ; otherwise, the while loop looks for x in L[500]...L[999 ]. Suppose that x < L[499]. Then the next iteration of the while loop looks for x in L[0]...L[498].

41 Suppose that x  L[249]. Suppose that x > L[249]. The next iteration of the while loop searches for x in L[250]...L[498].

42  Every iteration of the while loop cuts the size of the search list in half.  1000  1024 = 2 10.  The while loop will have at most 11 iterations to determine whether x is in L.  Every iteration of the while loop makes 2 key (item) comparisons the binary search will make at most 22 key comparisons to determine whether x is in L.  Sequential search, on average, will make 500 key comparisons to determine whether x is in L.  Suppose that L is of size 1000000.  1000000  1048576 = 2 20  The while loop in the binary search will have at most 21 iterations to determine whether an element is in L.  To determine whether an element is in L, the binary search makes at most 42 key comparisons.  Sequential search will make 500,000 key (item) comparisons to determine whether an element is in L.

43 TWO- AND MULTIDIMENSIONAL ARRAYS

44 Two-dimensional Array: A two-dimensional array is a collection of a fixed number of components arranged in two dimensions, and all components are of the same type. The syntax for declaring a two-dimensional array is: dataType arrayName[intexp1][intexp2]; where intexp1 and intexp2 are expressions yielding positive integer values. The two expressions intexp1 and intexp2 specify the number of rows and the number of columns, respectively, in the array. double sales[10][5]; declares a two-dimensional array sales of 10 rows and 5 columns and every component is of the type float.

45

46 Accessing Array Components The syntax to access a component of a two-dimensional array is arrayName[indexexp1][indexexp2] where indexexp1 and indexexp2 are expressions yielding nonnegative integer values. indexexp1 specifies the row position and indexexp2 specifies the column position. The statement sales[5][3] = 25.75; stores 25.75 into row numbered 5 and column numbered 3 (that is, 6th row and 4th column) of the array sales. If int i = 5; int j = 3; then the previous statement is equivalent to sales[i][j] = 25.75;

47

48 Two-Dimensional Array Initialization During Declaration Like one-dimensional arrays, two-dimensional arrays can be initialized when they are declared. int board[4][3] = {{2, 3, 1}, {15, 25, 13}, {20,4,7}, {11,18,14}};

49 To initialize a two-dimensional array when it is declared 1.The elements of each row are enclosed within braces and separated by commas. 2.All rows are enclosed within braces. 3.For number arrays, if all components of a row are not specified, the unspecified components are initialized to zero.

50 Two-dimensional Arrays and Enumeration Types We can also use enumeration type for array indices. Consider the following statements. const int rows = 6; const int colms = 5; enum carType{GM, Ford, Toyota, BMW, Nissan, Volvo}; enum colorType{Red, Brown, Black, White, Gray}; int inStock[rows][colms]; inStock[1][3] = 15; is equivalent to the statement inStock[Ford][White] = 15;

51

52

53 Processing Two-dimensional Arrays A two-dimensional array can be processed in three different ways. 1. Process the entire array. 2. Process a particular row of the array, called row processing. 3. Process a particular column of the array, called column processing.

54 const int rows = 7; const int columns = 6; int matrix[rows][columns]; int row; int col; int sum; int largest; int temp;

55

56 Each row and each column of a two-dimensional array is a one- dimensional array. When processing a particular row or column of a two-dimensional array we employ algorithms similar to process one-dimensional arrays.

57 Suppose that we want to process row number, say 5 of matrix. The components of row number 5 of matrix are: matrix[5][0], matrix[5][1], matrix[5][2], matrix[5][3], matrix[5][4], matrix[5][5]

58 In these components the first index is fixed at 5. The second index ranges from 0 to 5. The following for loop processes row number 5. for(col = 0; col < columns; col++) process matrix[5][col] This for loop is equivalent to the following for loop row = 5; for(col = 0; col < columns; col++) process matrix[row][col]

59 Similarly, suppose that we want to process column number 2 of matrix, that is, the third column of matrix. The components of this column are: matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2], matrix[4][2], matrix[5][2], matrix[6][2]

60 The second index is fixed at 2 and the first index ranges from 0 to 6. The following for loop processes column 2 of matrix. for(row = 0; row < rows; row++) process matrix[row][2] This for loop is equivalent to the following for loop col = 2; for(row = 0; row < rows; row++) process matrix[row][col]

61 Initialization Suppose we want to initialize row number 4 to zero. The following for loop initializes row four to zero. row = 4; for(col = 0; col < columns; col++) matrix[row][col] = 0; To initialize the entire matrix to zero, we can also put the first index, that is, the row position in a loop. The following nested for loops initialize each component of matrix to 0. for(row = 0; row < rows; row++) for(col = 0; col < columns; col++) matrix[row][col] = 0;

62 Print The following nested for loops print the components of matrix, one row per line. for(row = 0; row < rows; row++) { for(col = 0; col < columns; col++) cout<<setw(5)<<matrix[row][col]<<" "; cout<<endl; }

63 Input The following for loop inputs data in row number 4 of matrix. row = 4; for(col = 0; col < columns; col++) cin>>matrix[row][col]; By putting the row number in a loop we can input data in each component of the matrix. for(row = 0; row < rows; row++) for(col = 0; col < columns; col++) cin>>matrix[row][col];

64 Sum by Row The following for loop finds the sum of row number 4 of matrix. sum = 0; row = 4; for(col = 0; col < columns; col++) sum = sum + matrix[row][col]; By putting the row number in a loop we can find the sum of each row separately. //Sum of each individual row for(row = 0; row < rows; row++) { sum = 0; for(col = 0; col < columns; col++) sum = sum + matrix[row][col]; cout<<"Sum of row "<<row+1<<" = " <<sum<<endl; }

65 Sum by Column //Sum of each individual column for(col = 0; col < columns; col++) { sum = 0; for(row = 0; row < rows; row++) sum = sum + matrix[row][col]; cout<<"Sum of column "<<col+1<<" = " <<sum<<endl; }

66 Largest Element in Each Row and Each Column The following for loop determines the largest element in row number 4. row = 4; largest = matrix[row][0]; for(col = 1; col < columns; col++) if(largest < matrix[row][col]) largest = matrix[row][col];

67 //Largest element in each row for(row = 0; row < rows; row++) { largest = matrix[row][0]; for(col = 1; col < columns; col++) if(largest < matrix[row][col]) largest = matrix[row][col]; cout<<"Largest element of row "<<row+1 <<" = "<<largest<<endl; }

68 //Largest element in each column for(col = 0; col < columns; col++) { largest = matrix[0][col]; for(row = 1; row < rows; row++) if(largest < matrix[row][col]) largest = matrix[row][col]; cout<<"Largest element of col "<<col+1 <<" = "<<largest<<endl; }

69 Reversing Diagonal Suppose matrix is a square array, that is, the number of rows and the number of columns are the same. Then matrix has a main diagonal and an opposite diagonal. const int rows = 4; const int columns = 4; The components of the main diagonal of matrix are: matrix[0][0], matrix[1][1], matrix[2][2], and matrix[3][3]. The components of the opposite diagonal are: matrix[0][3], matrix[1][2], matrix[2][1], and matrix[3][0].

70

71 After reversing both the diagonals, the array matrix is:

72 To reverse the main diagonal 1. Swap matrix[0][0] with matrix[3][3], and 2. Swap matrix[1][1] with natrix[2][2]. To reverse the opposite diagonal 1. Swap matrix[0][3] with matrix[3][0], and 2. Swap matrix[1][2] with natrix[2][1].

73 //Reverse main diagonal for(row = 0; row < rows / 2; row++) { temp = matrix[row][row]; matrix[row][row] = matrix[rows-1-row][rows-1-row]; matrix[rows-1-row][rows-1-row] = temp; } //Reverse the opposite diagonal for(row = 0; row < rows / 2; row++) { temp = matrix[row][rows-1-row]; matrix[row][rows-1-row] = matrix[rows-1-row][row]; matrix[rows-1-row][row] = temp; }

74 Passing Two-dimensional Arrays as Parameters to Functions Two-dimensional arrays can be passed as parameters to a function and they are passed by reference. The base address, that is, the address of the first component of the actual parameter is passed to the formal parameter. If matrix is the name of a two-dimensional array, then matrix[0][0] is the first component of matrix. When storing a two-dimensional array in the computer’s memory, C++ uses the row order form. That is, first the first row is stored, followed by the second row, which is followed by the third row and so on. When declaring a two-dimensional array as a formal parameter, we can omit the size of the first dimension, but not the second, that is, the number of columns must be specified.

75 Consider the following function definition: void example(int table[][5], int rowsize) {. } This function takes as a parameter a two-dimensional array of unspecified number of rows, but 5 columns. During the function call the number of columns of the actual parameter must match the number of columns of the formal parameter.

76 Arrays of Strings Arrays of Stings and the string Type string list[100]; Arrays of Strings and C- Strings (Character Arrays) char list[100][16];

77

78 strcpy(list[1], "Snow White"); for(j = 0; j < 100; j++) cout<<list[j]<<endl;

79 Other form of Declaring Two-dimensional Arrays const int numberOfRows = 20; const int numberOfColumns = 10; typedef int tableType[numberOfRows][numberOfColumns]; We can declare variables of the type tableType. tableType matrix; void initialize(tableType table) { int row; int col; for(row = 0; row < numberOfRows; row++) for(col = 0; col < numberOfColumns; col++) table[row][col] = 0; }

80 Multi-dimensional Arrays Array: An array is a collection of a fixed number of elements (called components) arranged in n dimensions (n >= 1), called an n - dimensional array. The general syntax of declaring an n -dimensional array is: dataType arrayName[intExp1][intExp2]...[intExpn]; where intExp1, intExp2, …, and intExpn are constant expressions yielding positive integer values.

81 The syntax of accessing a component of an n-dimensional array is: arrayName[indexExp1][indexExp2]...[indexExpn] where indexExp1, indexExp2,..., and indexExpn are expressions yielding nonnegative integer values. indexExpi gives the position of the array component in the ith dimension.

82 The statement double carDealers[10][5][7]; declares carDealers to be a three-dimensional array.  Size of the first dimension is 10 and it ranges from 0 to 9.  The size of the second dimension is 5 and it ranges from 0 to 4.  The size of the third dimension is 7 and it ranges from 0 to 6.  The base address of the array carDealers is the address of the first array component, that is the address of carDealers[0][0][0].  The total number of components in the array carDealers is 10*5*7 = 350.

83 carDealers[5][3][2] = 15564.75; for(i = 0; i < 10; i++) for(j = 0; j < 5; j++) for(k = 0; k < 7; k++) carDealers[i][j][k] = 0.0; initializes the entire array to 0.0.

84  When declaring a multi-dimensional array as a formal parameter in a function, we can omit the size of the first dimension but not the other dimensions.  As parameters multi-dimensional arrays are passed by reference only and a function cannot return a value of the type array.  There is no check if the array indices are within bounds.

85 PROGRAMMING EXAMPLE: ELECTION RESULTS The presidential election for the student council of your local university will be held soon. For reasons related to confidentiality, the chair of the election committee wants to computerize the voting. The chair is looking for someone to write a program to analyze the data and report the winner. Let us to write a program to help the election committee. The university has four major divisions and each division has several departments. For the purpose of the election, the four divisions, are labeled as Region 1, Region 2, Region 3, and Region 4. Each department in each division manages its own voting process and directly reports the votes received by each candidate to the election committee. The voting is reported in the following form: candidate_name region# number_of_votes_for_this_candidate

86 The election committee wants the output in the following tabular form. --------------Election Results-------------- Candidate Votes Name Region1 Region2 Region3 Region4 Total --------- ------- ------- ------- ------- ------ Balto 0 0 0 272 272 Doc 25 71 156 97 349. Winner: ???, Votes Received: ??? Total votes polled: ??? The names of the candidates in the output must be in alphabetical order. For this program we assume that there are six candidates seeking student council’s president post.

87 The data is provided in two files. One file, say candDat.txt consist the names of candidates seeking the president’s post. The names of the candidates in the file are in no particular order. In the second file each line consists of voting results in the following form: candidateName regionNumber numberOfVotesForThisCandidate For example, the input file looks like: Donald 1 23 Pluto 2 56 Doc 1 25 Pluto 4 23. The first line indicates that Donald received 23 votes from region 1.

88 Input: Two files, one containing candidates name and the other containing the votes data as described above. Output: Election results in a tabular form as described above and the winner.

89 Problem Analysis and Algorithm Design  The program must organize the voting data by region.  The program must also calculate the total number of votes received by each candidate as well as the total votes cast in the election.  The names of the candidates must appear in alphabetical order.  The data type of a candidate’s name (which is a string) and the data type of the number of votes (which is an integer) are different, we need two separate arrays—one to hold the candidates’ names and one to hold the voting data.  The array to hold the names of the candidates is a one-dimensional array, and each component of this array is a string.  Instead of using a single two-dimensional array to hold the voting data, we will use a two-dimensional array to hold the next four columns of the output and a one-dimensional array to hold the total votes received by each candidate.  These three arrays are parallel arrays.

90

91 1. Read the candidates’ names into the array candidatesName  2. Sort the array candidatesName. 3. Initialize the arrays votesByRegion and totalVotes  4. Process the voting data. 5. Calculate the total votes received by each candidate. 6. Output the results.

92 Function getCandidatesName void getCandidatesName(ifstream& inp, string cNames[], int noOfRows) { int i; for(i = 0; i < noOfRows; i++) inp>>cNames[i]; //read candidate_name } After a call to this function, the arrays to hold the data are:

93

94 Function sortCandidatesName This function uses selection sort algorithm (As discussed in this chapter) to sort the array candiatesName. void sortCandidatesName(string cNames[], int noOfRows) { int i, j; int min; //selection sort for(i = 0; i < noOfRows - 1; i++) { min = i; for(j = i + 1; j < noOfRows; j++) if(cNames[j] < cNames[min]) min = j; cNames[i].swap(cNames[min]); }

95

96 Function initialize

97 void initialize(int vbRegion[][noOfRegions], int tVotes[], int noOfRows) { int i,j; for(i = 0; i < noOfRows; i++) for(j = 0; j < noOfRegions; j++) vbRegion[i][j] = 0; for(i = 0; i < noOfRows; i++) tVotes[i] = 0; }

98 Process Voting Data For each entry in the file voteDat.txt, we do the following: 1.Get a candidateName, regionNumber, numberOfVotesForTheCandidate. 2. Find the row number in the array candidatesName corresponding to this candidate. This gives the corresponding row number in the array votesByRegion for this candidate. 3. Find the column in the array votesByRegion corresponding to the regionNumber. 4.Update the appropriate entry in the array votesByRegion by adding numberOfVotesForTheCandidate.

99 Suppose that the next entry read from the input file is: Donald 2 35 Suppose that the three arrays are:

100  We locate the row in the above grid that corresponds to this candidate.  To find the row, we search the array candidatesName to find the row that corresponds to this name.  Donald corresponds to row number 2 in the array candidatesName.

101 votesByRegion[2][1] = votesByRegion[2][1] + 35;

102 Function binSearch int binSearch(string cNames[], int noOfRows, string name) { int first, last, mid; bool found; first = 0; last = noOfRows - 1; found = false; while(!found && first <= last) { mid = (first + last) / 2; if(cNames[mid] == name) found = true; else if(cNames[mid] > name) last = mid - 1; else first = mid + 1; } if(found) return mid; else return –1; }

103 Function processVotes : void processVotes(ifstream& inp, string cNames[], int vbRegion[][noOfRegions], int noOfRows) { string candName; int region; int noOfVotes; int loc; inp>>candName>>region>>noOfVotes;//Step a while(inp) { loc = binSearch(cNames,noOfRows,candName); //Step b if(loc != -1) vbRegion[loc][region - 1] = vbRegion[loc][region - 1] + noOfVotes; //Steps c and d inp>>candName>>region>>noOfVotes; //Step a }

104 Calculate Total Votes (Function addRegionsVote )

105

106 void addRegionsVote(int vbRegion[][noOfRegions], int tVotes[], int noOfRows) { int i,j; for(i = 0; i < noOfRows; i ++) for(j = 0; j < noOfRegions; j++) tVotes[i] = tVotes[i] + vbRegion[i][j]; }

107 Function printHeading void printHeading() { cout<<" --------------Election Results--------------" <<endl<<endl; cout<<"Candidate Votes"<<endl; cout<<"Name Region1 Region2 Region3 " <<"Region4 Total"<<endl; cout<<"--------- ------- ------- ------- ------- " <<"------"<<endl; }

108 Function printResults i. Initialize, sumVotes, largestVotes, and winLoc to 0. ii. For each row in each array a. i f ( largestVotes < tVotes[i]) { largestVotes = tVotes[i]; winLoc = i; } b. sumVotes = sumVotes + tVotes[i]; c. Output data from corresponding rows of each array. iii. Output the final lines of output.

109 void printResults(string cNames[], int vbRegion[][noOfRegions], int tVotes[], int noOfRows) { int i, j; int largestVotes = 0;//Step i int winLoc = 0;//Step i int sumVotes = 0; //Step i for(i = 0; i < noOfRows; i++)//Step ii { if(largestVotes < tVotes[i])//Step ii.a { largestVotes = tVotes[i]; winLoc = i; } sumVotes = sumVotes + tVotes[i];//Step ii.b //Step ii.c cout<<left; //output name left justified cout<<setw(9)<<cNames[i]<<" "; cout<<right;

110 for(j = 0; j < noOfRegions; j++) cout<<setw(8)<<vbRegion[i][j]<<" "; cout<<setw(6)<<tVotes[i]<<endl; } //step iii cout<<endl<<endl<<"Winner: "<<cNames[winLoc] <<", Votes Received: "<<tVotes[winLoc]<<endl <<endl; cout<<"Total votes polled: "<<sumVotes<<endl; }

111 Main Algorithm: Function main 1. Declare the variables 2. Open the input file candDat.txt. 3. If the input file does not exist, exit the program. 4. Read the data from the file candData.txt into the array candidatesName. 5. Sort the array candidatesName. 6. Close the file candDat.txt 7. Open the input file voteDat.txt. 8. If the input file does not exist, exit the program 9. Initialize the arrays, votesByRegion and totalVotes. 10. Process the voting data and store the results in the array votesByRegion.

112 11. Calculate the number of total votes received by each candidate and store the results in the array totalVotes. 12. Print the heading. 13. Print the results.

113 #include using namespace std; const int noOfCandidates = 6; const int noOfRegions = 4; void printHeading(); void initialize(int vbRegion[][noOfRegions], int tVotes[], int noOfRows); void getCandidatesName(ifstream& inp, string cNames[], int noOfRows); void sortCandidatesName(string cNames[], int noOfRows); int binSearch(string cNames[], int noOfRows, string name); void processVotes(ifstream& inp, string cNames[], int vbRegion[][noOfRegions], int noOfRows); void addRegionsVote(int vbRegion[][noOfRegions], int tVotes[], int noOfRows); void printResults(string cNames[], int vbRegion[][noOfRegions],int tVotes[], int noOfRows);

114 int main() { //Declare variables; Step 1 string candidatesName[noOfCandidates]; int votesByRegion[noOfCandidates][noOfRegions]; int totalVotes[noOfCandidates]; ifstream infile; infile.open("a:candData.txt");//Step 2 if(!infile)//Step 3 { cout<<"Input file (candData.txt) does not exit." <<endl; return 1; } getCandidatesName(infile, candidatesName, noOfCandidates); //Step 4 sortCandidatesName(candidatesName,noOfCandidates); //Step 5 infile.close();//Step 6 infile.open("a:voteData.txt");//Step 7

115 if(!infile)//Step 8 { cout<<"Input file (voteData.txt) does not exit." <<endl; return 1; } initialize(votesByRegion, totalVotes, noOfCandidates); //Step 9 processVotes(infile, candidatesName, votesByRegion, noOfCandidates); //Step 10 addRegionsVote(votesByRegion, totalVotes, noOfCandidates); //Step 11 printHeading(); //Step 12 printResults(candidatesName,votesByRegion, totalVotes,noOfCandidates); //Step 13 return 0; }

116 Definitions of remaining functions, discussed above and specified in the function prototypes, goes here.

117 Sample Run: --------------Election Results-------------- Candidate Votes Name Region1 Region2 Region3 Region4 Total --------- ------- ------- ------- ------- ------ Balto 0 0 0 272 272 Doc 25 71 156 97 349 Donald 110 158 0 0 268 Goofy 0 34 0 0 34 Mickey 112 141 156 89 498 Pluto 285 56 0 46 387 Winner: Mickey, Votes Received: 498 Total votes polled: 1808


Download ppt "CHAPTER 10 ARRAYS II Applications and Extensions."

Similar presentations


Ads by Google