In this article, we will learn to find the maximum of two numbers using a conditional operator in C programming.
The program takes two integer inputs from the user and prints the maximum of the two as a result.
Sample Input:
Enter first number: 20
Enter second number: 30
Output:
30 is the Largest
Before diving into the program, let’s first understand how the conditional operator works in C language.
The conditional operator which is also known as a ternary operator, takes three operands, the condition
, expression1
and expression2
:
condition ? expression1 : expression2;
If the condition
evaluates to true, the first expression i.e. expression1
executes, otherwise, the second expression i.e. expression2
executes.
We can also store the result of the conditional operator in a variable as follows:
variableName = condition ? expression1 : expression2;
The variable variableName
will hold the value of the expression1
if the condition evaluates to true, otherwise, it will hold the value of the expression2
.
To find the maximum of the two numbers using the conditional operators, you can use the following approach:
- Declare two integer variables
num1
andnum2
to store the two numbers. Also declare a third variablemax
which will hold the maximum of the two numbers. - Take the first number from the user using the scanf() function and store it in the
num1
variable. - Take the second number from the user using the scanf() function and store it in the
num2
variable. - Store the result of the conditional operator
num1 > num2?num1:num2;
in themax
variable. - The conditional operator returns
num1
if the num1 is greater than num2, otherwise, it returnsnum2
. - The maximum number is stored in the
max
variable. Print its value as a result.
The following program shows how you can use the conditional operator to find the maximum of the two numbers in C programming:
// C program to find the maximum of the two numbers // using the Conditional operator #include <stdio.h> int main(){ // Declare the variables int num1, num2, max; // Get the first number printf("Enter first number: "); scanf("%d", &num1); // Get the second number printf("Enter second number: "); scanf("%d", &num2); // Returns num1 if num1>num2, otherwise, returns num2 max = num1 > num2 ? num1 : num2; // Print the largest number(stored in max variable) printf("%d is the Largest", max); return 0; }
Output:
Enter first number: 20 Enter second number: 30 30 is the Largest
Please note that the above program does not give the correct output if both numbers are equal to each other.
If you also want to put the equality check on the two numbers, use the if...else
statements instead.
Thanks for reading.