In this article, we will learn how we can find the largest among three numbers using the conditional/ternary operator in C programming.
The program will take three integer inputs from the user and will print the maximum among them.
Sample Input:
Enter three numbers: 10 20 30
Expected Output:
Largest among the three numbers is 30
Before diving into the detailed explanation of the program, let’s first have a look at the ternary operator in C language.
The ternary or the conditional operator takes three operands, condition
, expression1
and expression2
:
condition ? expression1 : expression2;
If the condition evaluates to true, the first expression(expression1
) executes. Otherwise, the second expression i.e. expression2
executes.
You can also store the result of the ternary operator in any variable using the assignment(=
) operator. For example,
variableName = condition ? expression1 : expression2;
The variable variableName
will store the value of the expression1
if the condition evaluates to true, otherwise, it will store the value of the expression2
.
One of the interesting features of the ternary operator is that you can make the ternary operator nested. We will use this concept in our program.
This is how a typical nested ternary operator looks like in C:
condition ? (condition2 ? exp1 : exp2) : (condition3 ? exp1 : exp2);
To find the largest among the three numbers using the ternary operator, you can follow the below steps:
- Declare three integer variables
a
,b
&c
and use the scanf() function to get their values from the user. Also declare an integer variablemax
, which will hold the maximum of the three numbers. - Write a ternary operator with the condition
a > b
. If the value ofa
is greater thanb
, then the first expression of the ternary operator will be executed. - Inside the first expression, we have to check if
a
is also greater thanc
, if yes, thena
is the largest among the three. If not, eitherb
orc
is the largest. - Inside the second expression, we have to check if
b
is also greater thanc
, if yes, then it is the largest among the three, if not, thenc
is the largest. - Store the result of the ternary operator in the
max
variable and print the result using the printf() function.
The following example shows how you can use the ternary operator to find the largest among the three numbers in C:
// C program to find the maximum of the three numbers // using the Conditional/ternary operator #include <stdio.h> int main(){ // Declare the variables int a, b, c, max; // Get the three numbers from user printf("Enter three numbers: "); scanf("%d %d %d", &a, &b, &c); // Checks if a > b, if yes, exp1 executes, if not, exp2 executes max = a > b ? ( a > c ? a : c) : ( b > c ? b : c); // Print the result printf("Largest among the three numbers is %d", max); return 0; }
Output:
Enter three numbers: 10 20 30 Largest among the three numbers is 30
Thanks for reading.