Largest of two numbers using conditional operator
Introduction:
Write a C Program to find the largest of two numbers using the conditional operator in C Language.
The program should accept two numbers and find the largest. The program should use only the C Language conditional operator.
Examples:
Input:
1 |
Enter values of a and b : 100 200 |
Output:
1 |
Larger of 100 and 200 is 200 |
Syntax Conditional Operator in C:
Condition ? TrueExpression : FalseExpression
If the Condition is True then the TrueExpression will be executed.
Similarly, If the Condition is false, Then FalseExpression will be executed.
We can have nested conditional Operators in C Langauge.
We have discussed the conditional operators in detail in the following post – C Language: Conditional Operator (? 🙂 Tutorial | Ternary Operator/ Conditional operator tutorial with Examples – SillyCodes
Largest of Two numbers in C Program :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include<stdio.h> int main(void) { int a,b,max; // Take input from the user printf("Enter values for a and b : "); scanf("%d%d", &a, &b); // Use the ternary Operator to calculate the Maximum max = a>b ? a : b; printf("Larger of %d and %d is %d \n", a, b, max); return 0; } |
Largest of Two numbers Program Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
venkey@venkey$ gcc ternary.c venkey@venkey$ ./a.out Enter values for a and b : 100 200 Larger of 100 and 200 is 200 venkey@venkey$ ./a.out Enter values for a and b : 400 32 Larger of 400 and 32 is 400 venkey@venkey$ ./a.out Enter values for a and b : 989 2344 Larger of 989 and 2344 is 2344 venkey@venkey$ ./a.out Enter values for a and b : 767 232 Larger of 767 and 232 is 767 venkey@venkey$ |
3 Responses
[…] have looked at the Program to find the Maximum of two numbers using the if else statement and conditional statements. In today’s article, We are going to write a C Program to find the maximum of two numbers […]
[…] C Program to Calculate Largest of two numbers using conditional operator […]
[…] C Program to Calculate Largest of two numbers using conditional operator […]