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

Each time the loop is executed, c is incremented by 10. Using this, we write Program P5.16 to

produce the table.

Program P5.16

#include <stdio.h>

int main() {

double c, f;

printf("Celsius Fahrenheit\n\n");

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

f = 32 + 9 * c / 5;

printf("%5.0f %9.0f\n", c, f);

}

}

An interesting part of the program are the printf statements. In order to get the temperatures

centered under the heading, we need to do some counting. Consider the heading

Celsius Fahrenheit

with the C in column 1 and 2 spaces between s and F.

Assume we want the Celsius temperatures lined up under i and the Fahrenheit temperatures

lined up under n (see output above).

By counting, we find that i is in column 5 and n is in column 15.

From this, we can figure out that the value of c must be printed in a field width of 5 (the first

5 columns) and the value of f must be printed in the next 10 columns. We use a field width of 9 for

f since there is already one space between f and % in printf(...).

We print c and f without a decimal point using 0 as the number of decimal places in the

format specification. If any temperature is not a whole number, the 0 specification will print it

rounded to the nearest whole number, as in the table below.

Celsius Fahrenheit

20 68

22 72

24 75

26 79

28 82

30 86

32 90

34 93

36 97

38 100

40 104

130

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!