calculate max of three numbers using ternary operator in c
Calculating the Maximum of Three Numbers Using Ternary Operator in C
To calculate the maximum of three numbers using the ternary operator in C, you can use the following expression:
max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);
Let's break down the expression step by step:
- Condition 1: Check if
num1
is greater thannum2
. - If the condition is true, then:
- Sub-condition 1: Check if
num1
is greater thannum3
.- If true, assign
num1
tomax
. - If false, assign
num3
tomax
.
- If true, assign
- If the first condition is false, then:
- Sub-condition 2: Check if
num2
is greater thannum3
.- If true, assign
num2
tomax
. - If false, assign
num3
tomax
.
- If true, assign
This expression effectively compares the three numbers and assigns the maximum value to the variable max
using nested ternary operators.