0% found this document useful (0 votes)
1 views

Lab_4_6_Using_the_Conditional_Operator

Uploaded by

navid.panah1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Lab_4_6_Using_the_Conditional_Operator

Uploaded by

navid.panah1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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.

The conditional expression is evaluated as follows: If expression1 evaluates to true,


the result of the conditional expression is expression2. Otherwise, the result of the
conditional expression is expression3.

Objectives
In this lab, you rewrite if…else statements using the conditional operators (?:).

After completing this lab, you will be able to:


• Write if…else statements using the conditional operators (?:).

Estimated completion time: 10–15 minutes


Lab 4.6 Steps: Using the Conditional Operator (?:)

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”;

You might also like