Table of Contents
Introduction
This program of C++ programming will find the largest number among the three numbers entered by the user.
Here we will use a nested if-else statement.
Moreover, to understand this program, you should know about
1. Operators
2. nested if-else statement
Program
#include<iostream> using namespace std; int main() { float x,y,z; cout<<"Enter three values\n"; cin>>x>>y>>z; if(x>=y) // if x is greater than y { if(x>=z) // if x is greater than z { cout<<x<<" is largest among all."<<endl; } else { cout<<z<<" is largest among all."<<endl; } } else if(y>=x) // if y is greater than x { if(y>=z) // if y is greater than z { cout<<y<<" is largest among all."<<endl; } else { cout<<z<<" is largest among all."<<endl; } } else // else z is greater { cout<<z<<" is largest among all."<<endl; } return 0; }
Output
Explanation
The program asks the user to enter three values, and that values get stored in ‘x’, ‘y’, and ‘z’.
The values entered by the user are x=100, y=1102, and z=100.
if(x>=y)
firstly, we check whether x is greater than or equal to y or not. If it is true then the body of the ‘if’ statement is executed. In its body, we will check whether x is greater than or equal to z using the if(x>z) statement. If it gives a true result, it means ‘x’ is the greatest among all three.
If the above statement is false, then the else if statement i.e.
else if(y>=x) will be executed, and the same process will be followed as above.
If this statement also gives a false result, then the last statement i.e.
else
{
cout<<z<<” is largest among all.”<<endl;
}
gets executed.
0 Comments