Exercise 1-4

Write a program to print the corresponding Celsius to Fahrenheit table.

Using the previous program as a reference, we can define the variables lower, upper, and step to represent the lower bounds, upper bounds, and the step size, as well as celsius and fahr to store the temperatures.

    #include <stdio.h>
    
    main()
    {
        float fahr, celsius;
        int lower, upper, step;
    
        lower = 0;      /* lower limit of temperature table */
        upper = 300;    /* upper limit */
        step = 20;      /* step size */
    }

Because we want to print a table that converts Celsius temperatures into Fahrenheit, we initialize celsius to lower and set the condition of our while-loop to celsius <= upper, whilst incrementing celsius by step at the end of each iteration. This way, the value of celsius starts at lower and increments by step repeatedly until it reaches upper.

    #include <stdio.h>
    
    main()
    {
        float fahr, celsius;
        int lower, upper, step;
    
        lower = 0;      /* lower limit of temperature table */
        upper = 300;    /* upper limit */
        step = 20;      /* step size */
    
        celsius = lower;
        while (celsius <= upper)
            celsius = celsius + step;
    }

The Fahrenheit-Celsius program subtracted 32 from fahr and multiplied the result by 5/9 to get the corresponding Celsius temperature, so in order to convert celsius to fahr, we have to multiply celsius by 9/5 and then add 32. This can be written as the expression (9.0/5.0) * celsius + 32.0. Once we assign the converted temperature to fahr, we can print the Celsius column on the left and the Fahrenheit column on the right to better reflect the fact that we are converting from Celsius to Fahrenheit.

    #include <stdio.h>
    
    main()
    {
        float fahr, celsius;
        int lower, upper, step;
    
        lower = 0;      /* lower limit of temperature table */
        upper = 300;    /* upper limit */
        step = 20;      /* step size */
    
        printf("Celsius Fahr\n");
        celsius = lower;
        while (celsius <= upper) {
            fahr = (9.0/5.0) * celsius + 32.0;
            printf("%7.0f %4.0f\n", celsius, fahr);
            celsius = celsius + step;
        }
    }

Note: we do not need to print the decimal places of fahr since a multiple of twenty—our step size—times 9/5 will always be an integer.