Howdy readers, today you will learn how to find the largest of two numbers using the ternary operator in C Programming language.

We use ternary operator for decision making in place of longer if and else conditional statements.
Syntax
Condition ? valueIfTrue : ValueIfFalse
The ternary operator take three arguments:
- The first is a comparison argument.
- The second is the result upon a true statement.
- The third is the result upon a false statement.
So, without any delay, let’s begin this tutorial.
C Program to Find Largest of Two Numbers Using Ternary Operator
C Program
// C Program to Find Largest of Two Numbers Using Ternary Operator #include <stdio.h> int main(){ int num1, num2, result; // Asking for input printf("Enter the first number: "); scanf("%d", &num1); printf("Enter the second number: "); scanf("%d", &num2); // Using ternary operator result = num1 > num2 ? num1 : num2; // Displaying output printf("%d is the largest number.", result); return 0; }
Output
Enter the first number: 112
Enter the second number: 96
112 is the largest number.

Explanation
int num1, num2, result;
In this program, we have declared three int data type variables named num1, num2 and result.
// Asking for input printf("Enter the first number: "); scanf("%d", &num1); printf("Enter the second number: "); scanf("%d", &num2);
Then, the user is asked to enter two numbers.
// Using ternary operator result = num1 > num2 ? num1 : num2;
With the help of ternary operator, we find the largest number. The largest number gets stored in the result named variable.
// Displaying output printf("%d is the largest number.", result);
Finally, the largest of the two numbers is displayed on the screen using printf() function.
Conclusion
I hope after going through this post, you understand how to find the largest of two numbers using the ternary operator in C Programming language.
If you face any difficulty understanding this program, then let us know in the comment section. We will be delighted to solve your query.
Also Read: