C Program to find greatest among three numbers using Nested If-else
Objective
Write a C program to find the greatest among three numbers using Nested if-else statements.
Algorithm / Approach
- Read three numbers
a,b, andc. - Check the first condition:
if(a > b). - If true, dive into an inner (nested) block and check
if(a > c)to confirmais the absolute greatest. - If the first condition was false (meaning
bis larger thana), drop to the outerelseblock. - Inside that
elseblock, checkif(b > c)to see ifbbeatsc.
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) {
if(a>c)
printf("A is Greatest\n") ;
else
printf("C 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
- A Nested If is simply an if statement placed inside the body of another if (or else) statement.
- This approach avoids using the logical
&&operator. It branches the logic like a tree: first comparing two numbers, discarding the loser, and then comparing the winner against the third number.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)