C program to compare two numbers without using if-else statements :
This question is asked mostly on C programming interviews. Normally we use one if-else condition to check if a number is greater than another number or not like below :
#include <stdio.h>
int main()
{
int firstNo;
int secondNo;
printf("Enter first number : ");
scanf("%d", &firstNo);
printf("Enter second number : ");
scanf("%d", &secondNo);
if (firstNo > secondNo)
{
printf("%d is greater than %d\n", firstNo, secondNo);
}
else
{
printf("%d is smaller than %d\n", firstNo, secondNo);
}
}
But, we can also compare two numbers without using any if-else condition. Let’s take a look :
#include <stdio.h>
int main()
{
int firstNo;
int secondNo;
printf("Enter first number : ");
scanf("%d", &firstNo);
printf("Enter second number : ");
scanf("%d", &secondNo);
firstNo > secondNo ? printf("%d is greater than %d\n", firstNo, secondNo) : printf("%d is smaller than %d\n", firstNo, secondNo);
}
It will check if firstNo is greater than secondNo or not. If this condition is true, then it will execute the code after ’?’ i.e. the first printf statement. If this condition is false, it will execute the code afterr ’:’ i.e. the second printf statement. For example :
Enter first number : 12
Enter second number : 14
12 is smaller than 14
Enter first number : 15
Enter second number : 2
15 is greater than 2
For the first comparision, second printf is executed and for the second comparision, first printf is used