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

This means that before the computer gets to the for statement, n must have been assigned

some value and it is this value which determines how many times the loop is executed. If a value

has not been assigned to n, the for statement would not make sense and the program will crash

(or, at best, give some nonsensical output).

To illustrate, we can modify Program P5.11 to ask the user how many lines she wants to print.

The number entered is then used to control how many times the loop is executed and, hence,

how many lines are printed.

The changes are shown in Program P5.12.

Program P5.12

#include <stdio.h>

int main() {

int n;

printf("How many lines to print? ");

scanf("%d", &n);

printf("\n"); //print a blank line

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

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

}

A sample run is shown below. We will show shortly how to neaten the output.

How many lines to print? 12

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

6. I must not sleep in class

7. I must not sleep in class

8. I must not sleep in class

9. I must not sleep in class

10. I must not sleep in class

11. I must not sleep in class

12. I must not sleep in class

Note that we do not (and cannot) know beforehand what number the user will type. However,

that is not a problem. We simply store the number in a variable (n is used) and use n as the “final

value” in the for statement. Thus, the number the user types will determine how many times the

body is executed.

Now the user can change the number of lines printed simply by entering the desired value

in response to the prompt. No change is needed in the program. Program P5.12 is much more

flexible than P5.11.

124

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!