The program determines greatest among three numbers based on the conditional statements. It simply uses greater than (>) and smaller than (<) comparison operators to find greatest number. There are two ways to achieve this functionality. First one is by using if-else statement and other is using ternary operator.
It is required to find the largest numbers among three numbers. The solution is quite easy and simple :
In case of if-else statement, we have used nested if-else condition to find greatest of three numbers in the below C program.
Program:
#include <stdio.h> int main () { int num, num1, num2; printf ("Please enter first number : "); scanf ("%d", &num); printf ("Please enter second number : "); scanf ("%d", &num1); printf ("Please enter third number : "); scanf ("%d", &num2); printf ("\n******* Finding Greatest ******* \n"); if (num > num1) { if (num > num2) { printf ("\n%d is Greatest \n", num); } else { printf ("\n%d is Greatest \n", num2); } } else if (num1 > num2) { printf ("\n%d is Greatest \n", num1); } else { printf ("\n%d is Greatest \n", num2); } return 0; }
Output:
Please enter first number : 4 Please enter second number : 76 Please enter third number : 43 ******* Finding Greatest ******* 76 is Greatest
1) Taking three variables named num,num1,num2 assigned with 4,20,5 values respectively
2) if ‘num’ is greater than num1 and num2 then it would be printed as the largest number
3) if ‘num’ is smaller than num1, ‘else-if’ block would be executed that check if num1 is greater than ‘num’ or not
4) if it returns false, in that case, ”else’ block would be executed and “num2” become the greatest
program :
#include <stdio.h> int main () { int num, num1, num2; printf ("Please enter first number : "); scanf ("%d", &num); printf ("Please enter second number : "); scanf ("%d", &num1); printf ("Please enter third number : "); scanf ("%d", &num2); printf ("\n******* Finding Greatest ******* \n"); (num > num1) ? ( (num > num2)? printf ("\n%d is Greatest \n", num): printf ("\n%d is Greatest \n", num2) ) : ( (num1 > num2) ? printf ("\n%d is Greatest \n", num1): printf ("\n%d is Greatest \n", num2)); return 0; }
Output :
Please enter first number : 4 Please enter second number : 87 Please enter third number : 109 ******* Finding Greatest ******* 109 is Greatest
In the above example, we used ternary operator with same approach to find greatest number.
This post was last modified on August 12, 2022