C++ Program to Find Largest Number Among Three Numbers

In this example, you'll learn 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:


In this program, the 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 a proper message.

This program can be written in more than one way.


Example 1: Find Largest Number Using if...else Statement

#include <iostream>
using namespace std;

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

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

    // check if n1 is the largest number
    if(n1 >= n2 && n1 >= n3)
        cout << "Largest number: " << n1;

    // check if n2 is the largest number
    else if(n2 >= n1 && n2 >= n3)
        cout << "Largest number: " << n2;
    
    // if neither n1 nor n2 are the largest, n3 is the largest
    else 
        cout << "Largest number: " << n3;
  
    return 0;
}

Output

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

Example 2: Find the Largest Number Using Nested if...else statement

#include <iostream>
using namespace std;

int main() {

    double n1, n2, n3;

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

    // check if n1 is greater than n2
    if (n1 >= n2) {

        // if n1 is also greater than n3,
        // then n1 is the largest number
        if (n1 >= n3)
            cout << "Largest number: " << n1;

        // but if n1 is less than n3
        // but n1 is greater than n2
        // then n3 is the largest number
        else
            cout << "Largest number: " << n3;
    }

     // else, n2 is greater than n1
    else {

        // if n2 is also greater than n3,
        // then n2 is the largest number
        if (n2 >= n3)
            cout << "Largest number: " << n2;

        // but if n2 is less than n3
        // but n2 is greater than n1
        // then n3 is the largest number
        else
            cout << "Largest number: " << n3;
    }

    return 0;
}

Output

Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3
Did you find this article helpful?