08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10 ■ Structures

To find the winner, we must first find the largest value in the array. To do this, we will call a

function getLargest as follows:

int win = getLargest(candidate, 1, MaxCandidates);

This will set win to the subscript of the largest value in the numVotes field from candidate[1]

to candidate[7] (since MaxCandidates is 7):

In our example, win will be set to 3 since the largest value, 6, is in position 3. (6 is also in

position 5, but we just need the largest value, which we can get from either position.)

Here is getLargest:

int getLargest(PersonData person[], int lo, int hi) {

//returns the index of the highest vote from person[lo] to person[hi]

int big = lo;

for (int h = lo + 1; h <= hi; h++)

if (person[h].numVotes > person[big].numVotes) big = h;

return big;

} //end getLargest

Now that we know the largest value is in candidate[win].numVotes, we can “step through”

the array, looking for those candidates with that value. This way, we will find all the candidates, if

there is more than one, with the highest vote and declare them as winners.

An outline of printResults is as follows:

printResults

print the number of voters, valid votes and spoilt votes

print the score of each candidate

determine and print the winner(s)

300

The details are given in the function printResults:

void printResults(PersonData person[], int max, VoteCount c, FILE*out) {

int getLargest(PersonData[], int, int);

fprintf(out, "\nNumber of voters: %d\n", c.valid + c.spoilt);

fprintf(out, "Number of valid votes: %d\n", c.valid);

fprintf(out, "Number of spoilt votes: %d\n", c.spoilt);

fprintf(out, "\nCandidate Score\n\n");

for (int h = 1; h <= max; h++)

fprintf(out, "%-15s %3d\n", person[h].name,

person[h].numVotes);

fprintf(out, "\nThe winner(s)\n");

int win = getLargest(person, 1, max);

int winningVote = person[win].numVotes;

for (int h = 1; h <= max; h++)

if (person[h].numVotes == winningVote) fprintf(out, "%s\n",

person[h].name);

} //end printResults

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!