Which expression correctly assigns the maximum of a and b to m using the ternary operator?

Enhance your programming skills with the RECF Programming Test. Features flashcards and multiple choice questions with hints and explanations. Prepare for success!

Multiple Choice

Which expression correctly assigns the maximum of a and b to m using the ternary operator?

Explanation:
Using the ternary operator, you choose between two values based on a condition. To get the maximum of a and b, check if a is greater than b; if true, the maximum is a, otherwise it’s b. So the expression is int m = (a > b) ? a : b;. The parentheses around the condition help readability and ensure the comparison is evaluated before selecting the result. The alternative form that swaps the branches would return the smaller value when a > b, which is not the max.

Using the ternary operator, you choose between two values based on a condition. To get the maximum of a and b, check if a is greater than b; if true, the maximum is a, otherwise it’s b. So the expression is int m = (a > b) ? a : b;. The parentheses around the condition help readability and ensure the comparison is evaluated before selecting the result. The alternative form that swaps the branches would return the smaller value when a > b, which is not the max.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy