In this program, we will learn to find the largest number among the three numbers given by the user.
To understand this, you should have knowledge of-
- Variables
- How to take user input
- if…else if…else conditional statement
- && operator
- Ternary operator
We will do this program by 2 methods-
- Using if…else if…else statement
- Using the ternary operator
Program 1(Using an if…else if…else statement)
#include<iostream>
using namespace std;
int main()
{
int x , y, z, res;
cout<<"Enter first number - ";
cin>>x;
cout<<"Enter second number - ";
cin>>y;
cout<<"Enter third number ";
cin>>z;
if(x>=y && x>=z)
{
res = x;
}
else if(y>=x && y>=z)
{
res = y;
}
else
{
res = z;
}
cout<<"The largest number is: "<<res;
return 0;
}
Output:
Enter first number: 4
Enter second number: 7
Enter third number: 2
The largest number is: 7
Explanation:
- When this program runs, the user will see three subsequent messages to enter three numbers. Those numbers will be stored in the variables named x, y, and z respectively.
- Then, we made an if…else if…else tree to find out the largest number. In the if statement, we have written two conditions separated by the && operator. The && operator returns true if both the conditions are true, or it returns false otherwise. What this means is, if both the conditions x >= y and x >= z are true, it will return true, and x will be considered the largest number.
- The same is with the else if statement. If both the conditions written inside it are true, y will be considered the largest number.
- If both if and else if statements returned false, the else statement will be evaluated, and z will be considered as the largest number.
Program 2(Using the ternary operator)
Note: The ternary operator is also called as a conditional operator.
Syntax: (Expression 1 ) ? Expression2 : Expression3
In this, the operator returns one of the two values. Here if Expression 1 is evaluated to true then Expression 2 is evaluated and its result is returned but if expression 1 is false, then Expression 3 will be evaluated and its result will be returned.
#include<iostream>
using namespace std;
int main()
{
int x, y, z, res;
cout<<"Enter first number: ";
cin>>x;
cout<<"Enter second number: ";
cin>>y;
cout<<"Enter third number: ";
cin>>z;
res = ( x > y && x > z ) ? x : (y > z ? y : z);
cout<<"The largest number is: "<<res<<endl;
return 0;
}
Output:
Enter first number: 4
Enter second number: 7
Enter third number: 2
The largest number is: 7