"The C Programming Language", 2nd edition, Kernighan and Ritchie

Answer to Exercise 1-5, page 14

Solutions by Richard Heathfield and Chris Sidi

Modify the temperature conversion program to print the table in reverse order, that is, from 300 degrees to 0.

This version uses a while loop:
#include <stdio.h>

int main(void)
{
  float fahr, celsius;
  int lower, upper, step;

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

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


This version uses a for loop:
#include <stdio.h>

int main(void)
{
  float fahr, celsius;
  int lower, upper, step;

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

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


Chris Sidi notes that Section 1.3 Has a short For statement example, and "Based on that example, I think the solution to 1.5:
a) should do fahr to celsius conversion (whereas the solutions on your page do celsius to fahr)
b) should be similar to the example and as small." He offers this solution:
#include <stdio.h>

/* print Fahrenheit-Celsius table */
int
main()
{
     int fahr;

     for (fahr = 300; fahr >= 0; fahr = fahr - 20)
             printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));

   return 0;
}

Back to index





You are visitor number - call again soon!