So far, you have learned how to use
if-else
statements to execute one of two embedded
computation-performing
statements. You should also know about C's
conditional operator, which enables you to compute a value from one
of two embedded, value-producing expressions.
The conditional operator sees frequent service in display statements, where it helps you to produce the proper singularplural distinctions. Consider, for example, the following program, which displays a price change:
#includemain ( ) { int change; scanf ("%i", &change); if (change == 1) printf ("The price has changed by %i point.\n", change); else printf ("The price has changed by %i points.\n", change); } --- Data --- 1 --- Result --- The price has changed by 1 point.
The program works, but most C programmers would be unhappy, because there are two separate output statements that are almost identical. Such duplication makes programs longer, and the longer a program is, the greater the chance that a bug will creep in.
Accordingly, it would be safer to move the variationthe part that produces either the word point or the word pointsinto a value-producing expression inside a single display statement.