Lab_4_6_Using_the_Conditional_Operator
Lab_4_6_Using_the_Conditional_Operator
:)
You can write certain if…else statements concisely by using the conditional operator in
C++. The conditional operator, written as ?:, is a ternary operator, which means that it
takes three arguments. For example, examine the following code:
int x = 10, sum = 0;
if(x == 10)
sum = x + 3;
else
sum = x – 3;
Can be written as:
int x = 10, sum = 0;
(x==10) ? sum = x + 3 : sum = x - 3;
In the preceding examples, sum would be assigned 13 because x is equal to 10. Notice that
this code does not use the reserved word if or a semicolon (;) after the true statement.
Objectives
In this lab, you rewrite if…else statements using the conditional operators (?:).
Rewrite the following if…else statements using the conditional operator (?:). Assume
these statements are part of a C++ program.
1. if (x > 10)
cout << “x is greater than 10\n”;
else
cout << “x is less than or equal to 10\n”;
2. if (x==6)
cout << “A match was found.\n”;
else
cout << “A match was not found.\n”;