Find the Largest of Three Numbers in C++

In this exercise, you will write a C++ program that compares three numbers and determines which one is the largest. The program will use `if-else` statements to compare the three input numbers and output the largest one.

This program demonstrates basic conditional logic and how to handle multiple comparisons. It allows the user to input three numbers, and the program will identify the largest of them.

Group

Flow Control in C++

Objective

1. Ask the user to input three numbers.
2. Use conditional statements to compare the numbers.
3. Output the largest number among the three.
4. If two or more numbers are equal and the largest, output the corresponding message.

Write a program that compares three numbers and finds the largest one.

Example C++ Exercise

 Copy C++ Code
#include <iostream> // Include the iostream library for input and output

using namespace std; // Use the standard namespace

// Main function - the entry point of the program
int main() {
    double num1, num2, num3; // Variables to store the three numbers

    // Ask the user for input
    cout << "Enter first number: ";
    cin >> num1; // Read the first number

    cout << "Enter second number: ";
    cin >> num2; // Read the second number

    cout << "Enter third number: ";
    cin >> num3; // Read the third number

    // Compare the numbers using if-else statements to find the largest
    if (num1 >= num2 && num1 >= num3) { // Check if num1 is the largest
        cout << "The largest number is: " << num1 << endl;
    }
    else if (num2 >= num1 && num2 >= num3) { // Check if num2 is the largest
        cout << "The largest number is: " << num2 << endl;
    }
    else { // If the previous conditions are false, num3 must be the largest
        cout << "The largest number is: " << num3 << endl;
    }

    return 0; // Return 0 to indicate that the program executed successfully
}

 Output

Enter first number: 12
Enter second number: 7
Enter third number: 19
The largest number is: 19

//Or in case of equal numbers:
Enter first number: 8
Enter second number: 8
Enter third number: 6
The largest number is: 8

Share this C++ Exercise


More C++ Programming Exercises of Flow Control in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.