08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5 ■ Programs with Repetition Logic

Here, <expr1> consists of two assignment statements separated by a comma; <expr3>

consists of two expressions separated by a comma. This is very useful when two variables are

related and we want to highlight the relationship. In this case, the relationship is captured in one

place, the for statement. We can easily see how the variables are initialized and how they are

changed.

This feature comes in very handy when dealing with arrays. We will see examples in Chapter 8.

For now, we leave you with the example of printing all pairs of integers that add up to a given

integer, n.

The code is:

int lo, hi;

//assume n has been assigned a value

for (lo = 1, hi = n - 1; lo <= hi; lo++, hi--)

printf("%2d %2d\n", lo, hi);

1 9

2 8

3 7

4 6

5 5

If n is 10, this code will print the following:

The variables lo and hi are initialized to the first pair. After a pair is printed, lo is

incremented by 1 and hi is decremented by 1 to get the next pair. When lo passes hi, all pairs

have been printed.

5.15 The do...while Statement

We have seen that the while statement allows a loop to be executed zero or more times. However,

there are situations in which it is convenient to have a loop executed at least once. For example,

suppose we want to prompt for a number representing a day of the week, with 1 for Sunday, 2

for Monday, and so on. We also want to ensure that the number entered is valid, that it lies in the

range 1 to 7. In this case, at least one number must be entered. If it is valid, we move on; if not, we

must prompt again for another number and must do so as long as the number entered is invalid.

We could express this logic using a while statement as follows:

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

scanf("%d", &day); //assume int day

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

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

scanf("%d", &day);

}

132

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!