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.15

#include <stdio.h>

int main() {

int factor, start, finish;

printf("Type of table? ");

scanf("%d", &factor);

printf("From? ");

scanf("%d", &start);

printf("To? ");

scanf("%d", &finish);

printf("\n");

for (int m = start; m <= finish; m++)

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

}

The following sample run shows how to produce a “6 times” table from 10 to 16.

Type of table? 6

From? 10

To? 16

10 x 6 = 60

11 x 6 = 66

12 x 6 = 72

13 x 6 = 78

14 x 6 = 84

15 x 6 = 90

16 x 6 = 96

To cater for bigger numbers, we would need to increase the field width of 2 in the printf

statement if we want the numbers to line up neatly.

Comment on Program P5.15

The program assumes that start is less than or equal to finish. What if this is not so? For

example, suppose the user enters 20 for start and 15 for finish. The for statement becomes

for (int m = 20; m <= 15; m++)

m is set to 20; since this value is immediately bigger than the final value 15, the body is not

executed at all, and the program ends with nothing printed.

128

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!