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

On exit from the for loop, the value of h (6, in this case) is available and may be used by the

programmer, if required. Note, however, that if h was declared in the for statement, it would be

unavailable outside the loop.

If we need a loop to count backwards (from 5 down to 1, say), we can write

for (int h = 5; h >= 1; h--)

The loop body is executed with h taking on the values 5, 4, 3, 2, and 1.

We can also count upwards (or downwards) in steps other than 1. For example, the statement

for (int h = 10; h <= 20; h += 3)

will execute the body with h taking on the values 10, 13, 16 and 19. And the statement

for (int h = 100; h >= 50; h -= 10)

will execute the body with h taking on the values 100, 90, 80, 70, 60, and 50.

In general, we can use whatever expressions we need to get the effect that we want.

In Program P5.10, h takes on the values 1, 2, 3, 4, and 5 inside the loop. We have not used

h in the body but it is available, if needed. We show a simple use in Program P5.11 in which we

number the lines by printing the value of h.

Program P5.11

#include <stdio.h>

int main() {

for (int h = 1; h <= 5; h++)

printf("%d. I must not sleep in class\n", h);

}

When run, this program will print the following:

1. I must not sleep in class

2. I must not sleep in class

3. I must not sleep in class

4. I must not sleep in class

5. I must not sleep in class

The initial and final values in the for statement do not have to be constants; they can be

variables or expressions. For example, consider this:

for (h = 1; h <= n; h++) ...

How many times would the body of this loop be executed? We cannot say unless we know

the value of n when this statement is encountered. If n has the value 7, then the body would be

executed 7 times.

123

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!