Jul 21, 2014

K&R Exercise 1.3 Print heading to temperature conversion program

Problem Statement

Exercise 1-3: Modify the temperature conversion program to print a heading above the table.

Solution

First for reference let me write down the temperature conversion program, that is referred in question.


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

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

   fahr = lower;
   while(fahr <= upper) {
      celsius = (5.0/9.0) * (fahr - 32.0);
      printf("%3.0f %6.1f\n", fahr, celsius);
      fahr = fahr + step;
   }

   return 0;
}

Question is telling to print a heading above the table. Since the table heading occurs before all the entries. It should occur before while loop. Which can be done as follows.


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

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

   fahr = lower;
   printf("  C      F\n");
   printf("----------\n");
   while(fahr <= upper) {
      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
----------
  0  -17.8
 20   -6.7
 40    4.4
 60   15.6
 80   26.7
100   37.8
120   48.9
140   60.0
160   71.1
180   82.2
200   93.3
220  104.4
240  115.6
260  126.7
280  137.8
300  148.9

No comments :

Post a Comment