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

Program P5.14

#include <stdio.h>

int main() {

int factor;

printf("Type of table? ");

scanf("%d", &factor);

for (int m = 1; m <= 12; m++)

printf("%2d x %d = %2d\n", m, factor, m * factor);

}

Since we do not know beforehand what type of table would be requested, we cannot use 7,

say, in the format string, since the user may want a “9 times” table. We must print the variable

factor which holds the type of table.

The following is a sample run:

Type of table? 7

1 x 7 = 7

2 x 7 = 14

3 x 7 = 21

4 x 7 = 28

5 x 7 = 35

6 x 7 = 42

7 x 7 = 49

8 x 7 = 56

9 x 7 = 63

10 x 7 = 70

11 x 7 = 77

12 x 7 = 84

We now have a program that can produce any multiplication table from 1 to 12. But there is

nothing sacred about the range 1 to 12 (special, maybe, since that’s what we all learned in school).

How can we generalize the program to produce any table in any range? We must let the user tell

the program what type of table and what range he wants. And in the program, we will need to

replace the numbers 1 and 12 by variables, (start and finish, say).

All these changes are reflected in Program P5.15.

127

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!