C++ Program to Find Largest Number Among Three Numbers (Using nested if-else statement)

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.

 

Author

  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.