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 8 ■ Arrays

This is a clever way of using the vote v as a subscript to add 1 for the right candidate. For

example, if v is 3, we have a vote for candidate 3, Kamal Ramdhan. We wish to add 1 to the vote

count for candidate 3. This count is stored in vote[3]. When v is 3, the statement becomes

++vote[3];

This adds 1 to vote[3]. The beauty is that the same statement will add 1 for any of the

candidates, depending on the value of v. This illustrates some of the power of using arrays. It does

not matter whether there are 7 candidates or 700; the one statement will work for all.

Now that we know how to read and process the votes, it remains only to determine the

winner(s) and print the results. We will delegate this task to the function printResults.

Using the sample data, the array vote will contain the following values after all the votes have

been tallied (remember we are not using vote[0]).

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

getLargest (Section 8.13) with

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

This will set win to the subscript of the largest value from vote[1] to vote[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 the way the code is written, it will return the first position that contains

the largest, if there is more than one.)

Now that we know the largest value is in vote[win], we can ‘step through’ the array, looking

for those candidates with that value. This way, we will find all the candidates (one or more) with

the highest vote and declare them as winners.

The details are given in the function printResults shown as part of Program P8.8, our

solution to the voting problem posed at the beginning of this section.

Program P8.8

#include <stdio.h>

#include <string.h>

#define MaxCandidates 7

#define MaxNameLength 30

FILE *in, *out;

int main() {

char name[MaxCandidates + 1][MaxNameLength + 1];

int vote[MaxCandidates + 1];

int v, validVotes = 0, spoiltVotes = 0;

void initialize(char [][MaxNameLength + 1], int []);

void printResults(char [][MaxNameLength + 1], int [], int, int);

239

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!