225k views
0 votes
How does one use the ternary operator to get the max of two values:

A. max = (a > b) ? a : b
B. max = (a < b) ? a : b
C. max = (a >= b) ? a : b
D. max = (a <= b) ? a : b

User Kristel
by
8.1k points

1 Answer

6 votes

Final answer:

To use the ternary operator to determine the maximum of two values, option A: max = (a > b) ? a : b is the correct choice, where max will be assigned the value of a if a is greater than b, otherwise max will be assigned the value of b.

Step-by-step explanation:

To get the max of two values using a ternary operator, you should structure the statement to return the larger value when the condition is true. Given options A through D, the correct way to use the ternary operator for this purpose is as follows:

Option A. max = (a > b) ? a : b

This means that if a is greater than b, assign a to max; otherwise, assign b to max. The ternary operator acts as a shorthand for an if-else statement and is composed of three parts: the condition (a > b), the result if the condition is true (a), and the result if the condition is false (b).

User Avaris
by
7.9k points