ch1-for() variant (temperature)

Chapter_1     Exercise_1-4 Exercise_1-5







Note:  while() should be used when testing a condition, for() should be used when counting something.




fahr.c     K&R, p. 13         download


#include <stdio.h> // for printf()
// print Fahrenheit-Celsius table
int main()
{
int fahr;

for (fahr = 0; fahr <= 300; fahr += 20)
printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
}
/*
gcc fahr.c -o fahr
./fahr
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
*/





TIP:

It is always good coding practice to put braces around the body of a loop, like  while() or for(), even if the body contains a single statement. It is easier to read, to distinguish from other code, and you may add more statements to the body later on. In our program,
for (fahr = 0; fahr <= 300; fahr += 20)
{printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));}



Note:  Write
while(){i++;},  not
while(){i++}; // compile error









Chapter_1     Exercise_1-4 BACK_TO_TOP Exercise_1-5



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo