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

and so on. We want to let the user enter as many numbers as he wishes. Since we can have no

idea how many that will be, and the amount could vary from one run of the program to the next,

we must let the user “tell” us when he wishes to stop entering numbers.

How does he “tell” us? Well, the only time the user “talks” to the program is when he types

a number in response to the prompt. If he wishes to stop entering numbers, he can enter some

“agreed-upon” value; when the program reads this value, it will know that the user wishes to stop.

In this example, we can use 0 as the value that tells the program that the user wishes to stop.

When a value is used this way, it is referred to as a sentinel or end-of-data value. It is sometimes

called a rogue value—the value is not to be taken as one of the actual data values.

What can we use as a sentinel value? Any value that cannot be confused with an actual data

value would be okay. For example, if the data values are all positive numbers, we can use 0 or −1

as the sentinel value. When we prompt the user, it is a good idea to remind him what value to use

as the sentinel value.

Assume we want the program to run as follows:

Enter a number (0 to end): 24

Enter a number (0 to end): 13

Enter a number (0 to end): 55

Enter a number (0 to end): 32

Enter a number (0 to end): 19

Enter a number (0 to end): 0

The sum is 143

How do we get the program to run like that? We want to be able to express the following logic

in a form the computer could understand:

As long as the user does not enter 0, keep prompting him for another number and add it

to the sum

It seems obvious that we must, at least, prompt him for the first number. If this number is 0, we

must print the sum (which, of course, would be 0 at this time). If the number is not 0, we must add it

to the sum and prompt for another number. If this number is 0, we must print the sum. If this number

is not 0, we must add it to the sum and prompt for another number. If this number is 0..., and so on.

The process will come to an end when the user enters 0.

This logic is expressed quite neatly using a while construct (also called a while statement or

while loop):

//Algorithm for finding sum

set sum to 0

get a number, num

while num is not 0 do

add num to sum

get another number, num

endwhile

print sum

92

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!