Sams Teach Yourself C in 21 Days

(singke) #1
The Pieces of a C Program: Statements, Expressions, and Operators 77

4


25:
26: return 0;
27: }

Input an integer value for x: 99
Input an integer value for y: 8
x is greater than y
Input an integer value for x: 8
Input an integer value for y: 99

x is smaller than y
Input an integer value for x: 99
Input an integer value for y: 99
x is equal to y
Lines 18 through 24 are slightly different from the previous listing. Line 18 still
checks to see whether xequalsy. If xdoes equal y,x is equal to yappears on-
screen, just as in Listing 4.3 (List0403.C). However, the program then ends, and lines 20
through 24 aren’t executed. Line 21 is executed only if xis not equal to y, or, to be more
accurate, if the expression “x equals y” is false. If xdoes not equal y, line 21 checks to
see whether xis greater than y. If so, line 22 prints x is greater than y; otherwise
(else), line 24 is executed.
Listing 4.4 uses a nested ifstatement. Nesting means to place (nest) one or more C
statements inside another C statement. In the case of Listing 4.4, an ifstatement is part
of the first ifstatement’s elseclause.

TheifStatement
Form 1
if( expression)
{
statement1;
}
next_statement;
This is the ifstatement in its simplest form. If expressionis true,statement1is exe-
cuted. If expressionis not true,statement1is ignored.
Form 2
if( expression)
{

LISTING4.4 continued

INPUT/
OUTPUT

ANALYSIS

,


S

YNTAX

,


07 448201x-CH04 8/13/02 11:15 AM Page 77

Free download pdf