WAP 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 blocks.
Algorithm / Approach
- Read three integers.
- Create an outer
if (a > b)block. - Inside that block, create an inner
if (a > c)to confirmais the greatest, or anelseto declarecthe greatest. - Create an outer
elseblock (meaningb > a). - Inside that
elseblock, create an innerif (b > c)to confirmbis the greatest.
main.cpp
#include<iostream>
using namespace std;
int main() {
int a,b,c;
cout<<"Enter Values for A,B & C ";
cin>>a>>b>>c;
if(a>b) {
if(a>c)
cout<<"A is greatest";
else
cout<<"C is greatest";
}
else{
if(b>c)
cout<<"B is greatest";
else
cout<<"C is greatest";
}
return 0;
}
Expected Output
Enter Values for A,B & C 10 50 30 B is greatest
Explanation of the Program
- Nested conditionals are
if-elseblocks placed entirely inside otherif-elseblocks. - They are often used to break down complex logical trees into simpler steps, though they can make the code harder to read if nested too deeply compared to using logical operators like
&&.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)