C Program to find greatest among three numbers
Objective
Write a C program to find the greatest among three numbers using an if-else-if ladder.
Algorithm / Approach
- Declare three integer variables
a,b, andc. - Read the values from the user.
- Use the logical AND operator (
&&) to check ifais greater than bothbANDc. - If false, use
else if(b > c)to check ifbis the greatest. - If both previous conditions fail, then
cmust be the greatest (handled by the finalelse).
main.c
#include<stdio.h>
int main( ){
int a, b, c;
printf("Enter Values for A,B & C : ");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c) {
printf("A is Greatest\n") ;
}
else if(b>c){
printf("B is Greatest\n");
}
else {
printf("C is Greatest\n");
}
return 0;
}
Expected Output
Enter Values for A,B & C : 52 43 66 C is Greatest
Explanation of the Program
- An
if-else-ifladder is used when you need to check multiple conditions sequentially. - The Logical AND operator (
&&) ensures that the entire condition is only true if ALL individual conditions are true. - In the
else if(b > c)block, we don't need to check ifb > aagain, because ifawas the greatest, the very firstifstatement would have caught it and the ladder would have exited.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)