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 5 ■ Programs with Repetition Logic

We point out that we could write all our programs without using increment, decrement,

or the special assignment operators. However, sometimes, they permit us to express certain

operations more concisely, more conveniently, and, possibly, more clearly.

5.6 Find Largest

Suppose we want to write a program that works as follows: the user will type some numbers and

the program will find the largest number typed. The following is a sample run of the program

(underlined items are typed by the user):

Enter a number (0 to end): 36

Enter a number (0 to end): 17

Enter a number (0 to end): 43

Enter a number (0 to end): 52

Enter a number (0 to end): 50

Enter a number (0 to end): 0

The largest is 52

The user will be prompted to enter numbers, one at a time. We will assume that the numbers

entered are all positive integers. We will let the user enter as many numbers as she likes. However,

in this case, she will need to tell the program when she wishes to stop entering numbers. To do so,

she will type 0.

Finding the largest number involves the following steps:

• Choose a variable to hold the largest number; we choose bigNum.

• Initialize bigNum to a very small value. The value chosen should be such that

no matter what number is entered, its value would be greater than this initial

value. Since we are assuming that the numbers entered would be positive,

we can initialize bigNum to 0.

• As each number (num, say) is entered, it is compared with bigNum; if num is

greater than bigNum, then we have a bigger number and bigNum is set to this

new number.

• When all the numbers have been entered and checked, bigNum will contain

the largest one.

These ideas are expressed in the following algorithm:

set bigNum to 0

get a number, num

while num is not 0 do

if num is bigger than bigNum, set bigNum to num

get a number, num

endwhile

print bigNum

102

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!