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

To cater for this possibility, we can let the program validate the values of start and finish

to ensure that the “From” value is less than or equal to the “To” value. One way of doing this is to

write the following:

if (start > finish)

printf("Invalid data: From value is bigger than To value\n");

else {

printf("\n");

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

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

}

Validating data entered is yet another example of defensive programming. Also, it is better to

print a message informing the user of the error rather than have the program do nothing. This

makes the program more user friendly.

Another option here is not to treat a bigger start value as an error but simply print the table

in reverse order, going from largest to smallest. Yet another possibility is to swap the values of

start and finish and print the table in the normal way. These variations are left as exercises.

5.13 Temperature Conversion Table

Some countries use the Celsius scale for measuring temperature while others use the Fahrenheit

scale. Suppose we want to print a table of temperature conversions from Celsius to Fahrenheit.

The table runs from 0 degrees C to 100 degrees C in steps of 10, thus:

Celsius Fahrenheit

0 32

10 50

20 68

30 86

40 104

50 122

60 140

70 158

80 176

90 194

100 212

For a Celsius temperature, C, the Fahrenheit equivalent is 32 + 9C/5.

If we use c to hold the Celsius temperature, we can write a for statement to let c take on the

values 0, 10, 20, ..., up to 100, with

for (c = 0; c <= 100; c += 10)

129

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!