TheelseClause ..............................................................................................
Anifstatement can optionally include an elseclause. The elseclause is included as
follows:
if (expression)
statement1;
else
statement2;
Ifexpressionevaluates to true,statement1is executed. If expressionevaluates to
false, control goes to the elsestatement,statement2,which is then executed. Both
statement1andstatement2can be compound statements or blocks.
Listing 4.4 shows the program in Listing 4.3 rewritten to use an ifstatement with an
elseclause.
LISTING4.4 List0404.c. An ifstatement with an elseclause
1: /* Demonstrates the use of if statement with else clause */
2:
3: #include <stdio.h>
4:
5: int x, y;
6:
7: int main( void )
8: {
9: /* Input the two values to be tested */
10:
11: printf(“\nInput an integer value for x: “);
12: scanf(“%d”, &x);
13: printf(“\nInput an integer value for y: “);
14: scanf(“%d”, &y);
15:
16: /* Test values and print result */
17:
18: if (x == y)
19: printf(“x is equal to y\n”);
20: else
21: if (x > y)
22: printf(“x is greater than y\n”);
23: else
24: printf(“x is smaller than y\n”);
76 Day 4
You will notice that the statements within an ifclause are indented. This is
Note a common practice to aid readability.
07 448201x-CH04 8/13/02 11:15 AM Page 76