WAP to find greatest among three numbers
Objective
Write a C++ program to find the greatest among three numbers using the logical AND operator.
Algorithm / Approach
- Read three integers:
a,b, andc. - Check if
ais the greatest usingif (a > b && a > c). - Check if
bis the greatest usingelse if (b > c)(sinceais already eliminated). - If both are false,
cmust be the greatest, so use a finalelse.
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 && a>c) {
cout<<"A 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 29 20 B is greatest
Explanation of the Program
- The Logical AND operator (
&&) allows you to combine multiple conditions together. - For an
&&expression to be considered true, BOTH conditions on its left and right sides must be individually true. By chainingelse ifstatements, C++ evaluates them sequentially until it finds the first true condition, and then skips the rest.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)