Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating Expressions and Statements 95

4


15:
16: if (x > y)
17: z = x;
18: else
19: z = y;
20:
21: cout << “After if test, z: “ << z;
22: cout << “\n”;
23:
24: z = (x > y)? x : y;
25:
26: cout << “After conditional test, z: “ << z;
27: cout << “\n”;
28: return 0;
29: }

Enter two numbers.
First: 5

Second: 8

After if test, z: 8
After conditional test, z: 8
Three integer variables are created:x,y, and z. The first two are given values by
the user. The ifstatement on line 16 tests to see which is larger and assigns the
larger value to z. This value is printed on line 21.
The conditional operator on line 24 makes the same test and assigns zthe larger value. It
is read like this: “If xis greater than y, return the value of x; otherwise, return the value
of y.” The value returned is assigned to z. That value is printed on line 26. As you can
see, the conditional statement is a shorter equivalent to the if...elsestatement.

Summary ................................................................................................................


In today’s lesson, you have learned what C++ statements and expressions are, what C++
operators do, and how C++ ifstatements work.
You have seen that a block of statements enclosed by a pair of braces can be used any-
where a single statement can be used.
You have learned that every expression evaluates to a value, and that value can be tested
in an ifstatement or by using the conditional operator. You’ve also seen how to evaluate
multiple statements using the logical operator, how to compare values using the rela-
tional operators, and how to assign values using the assignment operator.

OUTPUT


LISTING4.9 continued


ANALYSIS
Free download pdf