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

A look at the output reveals that each line consists of three parts:

1. A number on the left that increases by 1 for each new line.

2. A fixed part " x 2 = " (note the spaces) that is the same for each line.

3. A number on the right; this is derived by multiplying the number on the

left by 2.

We can produce the numbers on the left by using this statement:

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

We then print m each time through the loop. And we can produce the number on the right by

multiplying m by 2.

Program P5.13 shows how to write it. When run, it will produce the table above.

Program P5.13

#include <stdio.h>

int main() {

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

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

}

Note the use of the field width 2 (in %2d) for printing m and m * 2. This is to ensure that the

numbers line up as shown in the output. Without the field width, the table would not look neat—

try it and see.

What if we want to print a “7 times” table? What changes would be needed? We would just

need to change the printf statement to

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

Similarly, if we want a “9 times” table, we would have to change the 7s to 9s. And we would

have to keep changing the program for each table that we want.

A better approach is to let the user tell the computer which table he wants. The program will

then use this information to produce the table requested. Now when the program is run, it will

prompt:

Enter type of table:

If the user wants a “7 times” table, he will enter 7. The program will then go ahead and

produce a “7 times” table. Program P5.14 shows how.

126

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!