Jul 21, 2014

K&R Exercise 1.5 Temperature conversion reverse order

Problem Statement

Exercise 1-5: Modify the temperature conversion program to print the table in reverse order, that is, from 300 to 0.


Solution

Program is referring to K&R Exercise 1.3 Print heading to temperature conversion program.

Here the initial value will 300 and final value will be 0. Instead of incrementing in the loop we have to decrement.


#include <stdio.h>
int main()
{
   float fahr, celsius;
   int lower, upper, step;

   lower = 0;
   upper = 300;
   step = 20;

   fahr = upper;
   printf("  C      F\n");
   printf("----------\n");
 
   while(fahr >= lower) {
      celsius = (5.0/9.0) * (fahr - 32.0);
      printf("%3.0f %6.1f\n", fahr, celsius);
      fahr = fahr - step;
   }
   return 0;
}

Output of the above program will look as follows


  C      F
----------
300  148.9
280  137.8
260  126.7
240  115.6
220  104.4
200   93.3
180   82.2
160   71.1
140   60.0
120   48.9
100   37.8
 80   26.7
 60   15.6
 40    4.4
 20   -6.7
  0  -17.8

No comments :

Post a Comment