Loading...
C++ Program to Find Largest Number Among Three Numbers.

C++ Program to Find Largest Number Among Three Numbers.

In this example, we will learn how to find the largest number among three numbers using if, if else and nested if else statements.

To understand this example, you should have the knowledge of the following C++ programming topics:

Program to Find Largest Number Among Three Numbers

  • In this program, user is asked to enter three numbers.
  • Then this program finds out the largest number among three numbers entered by user and displays it with proper message.
  • This program can be used in more than one way.

Example 1: Program to Find Largest Number Using if Statement.

#include <iostream>
using namespace std;
int main() {    
    float n1, n2, n3;

    cout << "Enter three numbers: ";
    cin >> n1 >> n2 >> n3;

    if(n1 >= n2 && n1 >= n3)
        cout << "Largest number: " << n1;

    if(n2 >= n1 && n2 >= n3)
        cout << "Largest number: " << n2;

    if(n3 >= n1 && n3 >= n2)
        cout << "Largest number: " << n3;
                                          
    return 0;
}

Output

Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

Example 2: Program to Find Largest Number Using if...else Statement.

#include <iostream>
using namespace std;

int main() {
    float n1, n2, n3;

    cout << "Enter three numbers: ";
    cin >> n1 >> n2 >> n3;

    if((n1 >= n2) && (n1 >= n3))
        cout << "Largest number: " << n1;
    else if ((n2 >= n1) && (n2 >= n3))
        cout << "Largest number: " << n2;
    else
        cout << "Largest number: " << n3;
    
    return 0;
}

Output

Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

Example 3: Program to Find Largest Number Using Nested if...else statement.

#include <iostream>
using namespace std;

int main() {
    float n1, n2, n3;

    cout << "Enter three numbers: ";
    cin >> n1 >> n2 >> n3;

    if (n1 >= n2) {
        if (n1 >= n3)
            cout << "Largest number: " << n1;
        else
            cout << "Largest number: " << n3;
    }
    else {
        if (n2 >= n3)
            cout << "Largest number: " << n2;
        else
            cout << "Largest number: " << n3;
    }

    return 0;
}

Output

Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

Example 4: Program to Find Largest Number Using ternary Operator.

#include <iostream>
using namespace std;
 
int main()
{
    float a, b, c, largest;
  
    cout << "Enter three numbers: ";
    cin >> a >> b >> c;
      
    largest = (a > b) ? (a > c ? a : b) : (b > c ? b : b)
    cout << "Largest Number " << largest;
      
    return 0;
}

Output

Enter three numbers: 2
10
6 
Largest number: 10

Next Example

We hope that this Example helped you develop better understanding of the concept of "Find Largest Number Among Three Numbers" in C++.

Keep Learning : )

In the next Example, we will learn about C++ Find the Roots of a Quadratic Equation.


- Related Topics