Wednesday 5 January 2011

The C Programming Language (K&R) 01x03—Convert Celsius to Fahrenheit For Loop (p. 15)—Exercise 1-5


Another blog entry as I work my way through the book “The C Programming Language” by Brian Kernighan and Dennis Ritchie aka K&R.

The reasons I’m doing it? To learn the language. To show others I know something about the C. To create notes for future reference where, on a blog, I can easily find an answer on something I did previously. To practice my writing of documentation and in general.

I am using Visual C++ 2010 and creating the code as a console application. At some point I will try other compilers, but that’s for another day.

This entry continues on the previous entry (here) where C code converted temperatures between Celsius and Fahrenheit.

K&R p. 15, For Loop

The code in 01x02 used a while loop to cycle through a series of temperatures. The new code uses the for loop to achieve the same results but with less code. I suspect this new code executes faster because there are fewer variables involved, but it’s just a guess.

Unlike other languages, it’s possible to use either the while or for loops to do the same thing. Both can operate while a certain condition is true. The benefit of the for loop is that it has a built-in increment counter (sort of).
 

Attempt #1

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

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

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

     // keep console windown open
     system("pause");

     // return some value
    return 0;
}

One variable is used instead of five.


Attempt #2

I was curious about changing the location of the declaration of the fahr variable and added it in the for loop. It works, but there is a difference. When fahr is declared in the for loop as here, the variable’s scoop is limited to the for statement. It can’t be used outside the for.
 
int main()
{
     //int fahr;
    
     for (int fahr = 0; fahr <= 300; fahr = fahr + 20)
           printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));

     // keep console windown open
     system("pause");

     // return some value
    return 0;
}

The output for both attempts is:



Exercise 1-5.

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

Exercise 1-5 suggests to modify the code so it loops through temps from 300 to 0 instead of 0 to 300. That’s not that difficult. Start at 300 and move in steps of -20 as long as fahr is positive.

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

     // keep console windown open
     system("pause");

     // return some value
    return 0;
}

Here’s the output.


No comments:

Post a Comment