Jump to: navigation, search

The C Programming Language, 2nd Edition, by Kernighan and Ritchie
Exercise 1.05 on page 14

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



Solution by Richard Heathfield

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;
}

Solution by Chris Sidi

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;
}
Personal tools