17
is done once, before the loop proper is entered. The second part is the
test or condition that controls the loop:
fahr <= 300
This condition is evaluated; if it is true, the body of the loop (here a single ptintf) is
executed. Then the increment step
fahr = fahr + 20
is executed, and the condition re-evaluated. The loop terminates if the condition has become
false. As with the while, the body of the loop can be a single statement or a group of
statements enclosed in braces. The initialization, condition and increment can be any
expressions.
The choice between while and for is arbitrary, based on which seems clearer. The for is
usually appropriate for loops in which the initialization and increment are single statements and
logically related, since it is more compact than while and it keeps the loop control statements
together in one place.
Exercise 1-5. Modify the temperature conversion program to print the table in reverse order,
that is, from 300 degrees to 0.
1.4 Symbolic Constants
A final observation before we leave temperature conversion forever. It's bad practice to bury
``magic numbers'' like 300 and 20 in a program; they convey little information to someone who
might have to read the program later, and they are hard to change in a systematic way. One
way to deal with magic numbers is to give them meaningful names. A #define line defines a
symbolic name or symbolic constant to be a particular string of characters:
#define name replacement list
Thereafter, any occurrence of name (not in quotes and not part of another name) will be
replaced by the corresponding replacement text. The name has the same form as a variable
name: a sequence of letters and digits that begins with a letter. The replacement text can be
any sequence of characters; it is not limited to numbers.
#include <stdio.h>
#define LOWER 0 /* lower limit of table */
#define UPPER 300 /* upper limit */
#define STEP 20 /* step size */
/* print Fahrenheit-Celsius table */
main()
{
int fahr;
for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
}
The quantities LOWER, UPPER and STEP are symbolic constants, not variables, so they do not
appear in declarations. Symbolic constant names are conventionally written in upper case so
they can ber readily distinguished from lower case variable names. Notice that there is no
semicolon at the end of a #define line.
1.5 Character Input and Output
We are going to consider a family of related programs for processing character data. You will
find that many programs are just expanded versions of the prototypes that we discuss here.
www.plcworld.cn