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

VoteCount processVotes(PersonData person[], int max, FILE *in, FILE *out) {

VoteCount temp;

temp.valid = temp.spoilt = 0;

int v;

fscanf(in, "%d", &v);

while (v != 0) {

if (v < 1 || v > max) {

fprintf(out, "Invalid vote: %d\n", v);

++temp.spoilt;

}

else {

++person[v].numVotes;

++temp.valid;

}

fscanf(in, "%d", &v);

} //end while

return temp;

} //end processVotes

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

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

302

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!