Easy Tutorial
❮ Cpp Comments Cpp Exceptions Handling ❯

C++ Example - Finding the Maximum of Three Numbers

C++ Examples

We input three numbers through the screen and find the largest one.

Example - Using if

#include <iostream>
using namespace std;

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

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

    if(n1 >= n2 && n1 >= n3)
    {
        cout << "The largest number is: " << n1;
    }

    if(n2 >= n1 && n2 >= n3)
    {
        cout << "The largest number is: " << n2;
    }

    if(n3 >= n1 && n3 >= n2) {
        cout << "The largest number is: " << n3;
    }

    return 0;
}

The output of the above program is:

Please enter three numbers: 2.3
8.3
-4.2
The largest number is: 8.3

Example - Using if...else

#include <iostream>
using namespace std;

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

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

    if((n1 >= n2) && (n1 >= n3))
        cout << "The largest number is: " << n1;
    else if ((n2 >= n1) && (n2 >= n3))
        cout << "The largest number is: " << n2;
    else
        cout << "The largest number is: " << n3;

    return 0;
}

The output of the above program is:

Please enter three numbers, separated by spaces: 2.3
8.3
-4.2
The largest number is: 8.3

Example - Using Nested if...else

#include <iostream>
using namespace std;

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

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

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

    return 0;
}

The output of the above program is:

Please enter three numbers, separated by spaces: 2.3
8.3
-4.2
The largest number is: 8.3

C++ Examples

❮ Cpp Comments Cpp Exceptions Handling ❯