## Wednesday, 19 January 2011

### The C Programming Language (K&R) 01x11—Func for Temp Convert—Exercise 1-15

Exercise 1-15 from “The C Programming Language” by Brian Kernighan and Dennis Ritchie aka K&R.

Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.

The first code for section 1.2 is here.

Adding a function to do the conversion calculation is straightforward. I added an argument to choose between converting from C to F or F to C.

Sample Code.

I am using Visual C++ 2010 and created the sample code as a console application.

// Function prototype.
float TempConv(int temp, bool direction);

// The standard library includes the system function.
#include <cstdlib>

// Standard I/O library.
#include <cstdio>

// Constants.
#define LOWER 0 /* lower limit of table */
#define UPPER 300 /* upper limit */
#define STEP 20 /* step size */

int main()
{
int temp;

// Create table of F to C.
printf("  F\t    C\n");
for (temp = LOWER; temp <= UPPER; temp = temp + STEP)
printf("%3d\t%6.1f\n", temp, TempConv(temp, true));

// Create table of C to F.
printf("\n\n  C\t    F\n");
for (temp = -20; temp <= 50; temp = temp + 5)
printf("%3d\t%6.1f\n", temp, TempConv(temp, false));

// Keep console window open.
system("pause");

// Return some value.
return 0;

} // end main

float TempConv(int temp, bool direction)
{
if (direction)
// Convert Farhenheit to Celcius/
return (5.0/9.0)*(temp-32.0);
else
// Convert Celcius to Farhenheit.
return temp * (9.0/5.0) + 32.0;
}

Output.