So I was just trying to write a C code for comparing numbers, which one of the three number is largest and which one is the smallest.
Then I found that I can use the ternary operator (ex: x < y ? num1 : num2),
so I thought yeah okay this will work and then I wrote this code:
#include <stdio.h>
int main(){
int num1, num2, num3, largest, smallest;
printf("Enter three integers: ");
scanf("%d %d %d", &num1, &num2, &num3);
//largest among three integers.
largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
printf("\nThe largest among the three is: %d", largest);
//smallest among three integers
smallest = num1 < num2 ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 : num3);
printf("\nThe smallest among the three is: %d", smallest);
return 0;
}
So, if I give input like num1 = 10, num2 = 20 and num3 = 30, then the output is
Enter three integers: 10 20 30
The largest among the three is: 30
The smallest among the three is: 10
But what happens when all these numbers are equal? Will the condition of the Ternary operator be true or false?
Enter three integers: 20 20 20
The largest among the three is: 20
The smallest among the three is: 20
I don't know what the condition but the program works fine nothing wrong the output is correct.
I am using this on windows 10 latest and gcc.exe (MinGW.org GCC-6.3.0-1) 6.3.0
I am sorry if this is a lame question but I didn't found anything about this.
>
larger operator is true
only if the left value is larger than the rigth value. Otherwise it will be false
Will the condition of the Ternary operator be true or false?
n = x > y ? x : y;
n
will be assigned with the value of x
if x
is larger than y
, otherwise (including the case when x == y
) it will be assigned with the value of y