08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10 ■ Structures

296

A file, votes.txt, contains the names of the candidates. The first name

is considered as candidate 1, the second as candidate 2, and so on. The

names are followed by the votes. Write a program to read the data and

evaluate the results of the election. Print all output to the file, results.txt.

Your output should specify the total number of votes, the number of

valid votes, and the number of spoiled votes. This is followed by the votes

obtained by each candidate and the winner(s) of the election.

Suppose the file votes.txt contains the following data:

Victor Taylor

Denise Duncan

Kamal Ramdhan

Michael Ali

Anisa Sawh

Carol Khan

Gary Olliverie

3 1 2 5 4 3 5 3 5 3 2 8 1 6 7 7 3 5

6 9 3 4 7 1 2 4 5 5 1 4 0

Your program should send the following output to results.txt:

Invalid vote: 8

Invalid vote: 9

Number of voters: 30

Number of valid votes: 28

Number of spoilt votes: 2

Candidate Score

Victor Taylor 4

Denise Duncan 3

Kamal Ramdhan 6

Michael Ali 4

Anisa Sawh 6

Carol Khan 2

Gary Olliverie 3

The winner(s):

Kamal Ramdhan

Anisa Sawh

We now explain how we can solve this problem using C structures. Consider these declarations:

typedef struct {

char name[31];

int numVotes;

} PersonData;

PersonData candidate[8];

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!