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

Note, particularly, that we get a number before we enter the while loop. This is to ensure that

the while condition makes sense the first time. (It would not make sense if num had no value.)

To find the sum, we need to:

• Choose a variable to hold the sum; we will use sum.

• Initialize sum to 0 (before the while loop).

• Add a number to sum (inside the while loop). One number is added each

time through the loop.

On exit from the loop, sum contains the sum of all the numbers entered.

The while construct lets us execute one or more statements repeatedly as long as some

condition is true. Here, the two statements

add num to sum

get another number, num

are executed repeatedly as long as the condition num is not 0 is true.

In pseudocode, the while construct is usually written as follows:

while <condition> do

statements to be executed repeatedly

endwhile

The statements to be executed repeatedly are called the body of the while construct

(or, simply, the body of the loop). The construct is executed as follows:

1. <condition> is tested.

2. If true, the body is executed and we go back to step 1; if false, we

continue with the statement, if any, after endwhile.

We now show how the algorithm is executed using the sample data entered above. For easy

reference, the data was entered in the following order:

24 13 55 32 19 0

Initially, num is undefined and sum is 0. We show this as follows:

num

sum 0

24 is entered and stored in num;

num is not 0 so we enter the while loop;

num (24) is added to sum (0), giving:

num 24 sum 24

93

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!