C++ Program to Find Largest Number Among Three Numbers

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

Also Read:

Before we wrap up, let's put your understanding of this example to the test! Can you solve the following challenge?

Challenge:

Write a function to find the largest of two numbers.

  • Return the larger number between num1 and num2.
  • For example, with num1 = 12 and num2 = 8, the return value should be 12.
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges