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

While this will work, we can express it a bit neater using a do...while statement.

The general form of the do...while statement in C is

do

<statement>

while (<expression>);

The words do and while, the brackets, and the semicolon are required. You must supply

<statement> and <expression>.

When a do...while is encountered,

1. <statement> is executed

2. <expression> is then evaluated; if it is true (non-zero), repeat from step

1. If it is false (zero), execution continues with the statement, if any, after

the semicolon.

As long as <expression> is true, <statement> is executed. It is important to note that because

of the way the construct is written, <statement> is always executed at least once.

Using do...while, we can express the logic above as follows:

do {

printf("Enter a day of the week (1-7): ");

scanf("%d", &day);

} while (day < 1 || day > 7); //as long as day is invalid

Note how much neater this looks. Here, <statement> is the block delimited by { and }, and

<expression> is day < 1 || day > 7.

We illustrate the use of do...while with two more examples.

5.15.1 Highest Common Factor

Previously, we wrote Program P5.2 to find the HCF of two integers using Euclid's algorithm. We

now rewrite the program using do...while to ensure that the two numbers entered are indeed

positive integers. We also re-code the algorithm using do...while instead of while. This is shown

as Program P5.17.

133

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!