Program to find the largest of three numbers using conditional operator

Write a program to find the largest of three numbers using a conditional operator or ternary operator.

Ternary Operator: (condition)?first:second.

If the condition is true then the result will be first, otherwise, the result will be second.

C Program

#include <stdio.h>
int main()
{
    int firstNumseondNumthirdNum;

    printf("Enter first number : ");
    scanf("%d", &firstNum);

    printf("Enter second number : ");
    scanf("%d", &seondNum);

    printf("Enter third number : ");
    scanf("%d", &thirdNum);

    int maximum = firstNum > seondNum   ? (firstNum > thirdNum ? firstNum : thirdNum)
                  : seondNum > thirdNum ? seondNum
                                        : thirdNum;

    printf("Largest is %d "maximum);
    return 0;
}
Input:
Enter first number : 20
Enter second number : 25
Enter third number : 24

Output:

Largest is 25 


No comments:

Post a Comment