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

Here is the function, getLargest:

int getLargest(int num[], int lo, int hi) {

int big = lo;

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

if (num[h] > num[big]) big = h;

return big;

} //end getLargest

The function assumes the largest number is in position lo, the first one, by setting big to

lo. In turn, it compares the numbers in locations lo+1 up to hi with the one in location big. If a

bigger one is found, big is updated to the location of the bigger number.

8.14 Find the Smallest Number

The function, getLargest, could be easily modified to find the smallest value in an array. Simply

change big to small, say, and replace > by <, giving this:

int getSmallest(int num[], int lo, int hi) {

int small = lo;

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

if (num[h] < num[small]) small = h;

return small;

} //end getSmallest

This function returns the location of the smallest element from num[lo] to num[hi], inclusive.

Later, we will show you how to use this function to arrange a set of numbers in ascending order.

We have shown how to find the largest and smallest values in an integer array. The procedure

is exactly the same for arrays of other types such as double, char, or float. The only change

that has to be made is in the declaration of the arrays. Keep in mind that when we compare two

characters, the ‘larger’ one is the one with the higher numeric code.

8.15 A Voting Problem

We now illustrate how to use some of the ideas just discussed to solve the following problem.

In an election, there are seven candidates. Each voter is allowed one vote

for the candidate of his/her choice. The vote is recorded as a number

from 1 to 7. The number of voters is unknown beforehand but the votes

are terminated by a vote of 0. Any vote that is not a number from 1 to 7 is

an invalid (spoilt) vote.

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.

235

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!