Ethical Hacking Programming, Blogging, Hosting, All Computer Software, PC Software Download, JAVA in hindi, HTML, PHP, C, C++, Free Learning, Software's Download, Technical Videos, Technical Tricks and Tips, How Make Money

Another Version of the Conversion Table Example in C programming class 5

Another Version of the Conversion Table Example



This variant of the conversion table example produces identical output to the first, but serves to introduce symbolic constants and the for-loop.

/* Fahrenheit to Celcius conversion table (K&R page 12) */ #include <stdio.h>
int main(void) 
{
float fahr, celsius; 
int lower, upper, step;

/* Set lower and upper limits of the temperature table (in Fahrenheit) along with the 
* table increment step-size */
lower = 0; 
upper = 300; 
step = 20;

/* Create conversion table using the equation: C = (5/9)(F - 32) */ fahr = lower;
while (fahr <= upper) { 
celsius = (5.0/9.0) * (fahr−32.0);
printf("%3.0f \t%6.1f\n", fahr, celsius); fahr += step;
}
}

This program uses several variables.  These must be declared at the top of a block, before any statements. Variables are specified types, which are int and float in this example.
Note, the * beginning line 10 is not required and is there for purely aesthetic reasons. These first three statements in the program initialise the three integer variables.
The floating-point variable fahr is initialised. Notice that the two variables are of different type (int and float). The compiler performs automatic type conversion for compatible types.
The while-loop executes while ever the expression (fahr <= upper) is TRUE. The operator <= means LESS THAN OR EQUAL TO. This loop executes a compound statement enclosed in braces— these are the three statements on lines 18-20.
This statement performs the actual numerical computations for the conversion and stores the result in the variable celcius.
The printf () statement consists of a format string and two variables fahr and celsius. The format string has two conversion specifiers, %3.0f and %6.1f, and two escape characters, tab and new-line. (The conversion specifier %6.1f, for example, formats a floating-point number allowing space for at least six digits and printing one digit after the decimal point.  See Section 13.1.1 for more information on printf() and conversion specifiers.)
The assignment operator += produces an expression equivalent to fahr = fahr + step.

Style note.  Comments should be used to clarify the code where necessary. They should explain intent and point-out algorithm subtleties. They should avoid restating code idioms. Careful choice of identifiers (i.e., variable names, etc) can greatly reduce the number of comments required to produce readable code.

Share:

Follow On YouTube