Find the Largest of Three Numbers If-Else Logic

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, handling cases where numbers might be equal.

Comparison Logic

1. Multiple Inputs

The program captures three independent values (double) to allow comparison between integers or floating-point numbers.

2. Logical AND

Uses the && operator to verify if a number is greater than or equal to both other numbers simultaneously.

3. Equality Handling

By using >=, the logic remains robust even when the user enters duplicate values for the maximum.

Objective

  • 1. Ask the user to input three numbers.
  • 2. Use conditional statements with logical operators to compare the numbers.
  • 3. Identify and output the largest number among the three.
  • 4. Ensure the program correctly handles cases where two or more numbers are identical.

Example C++ Exercise

find_largest.cpp If-Else Logic
#include <iostream> // Include the iostream library

using namespace std; // Use the standard namespace

int main() {
    double num1, num2, num3; // Variables to store the three numbers

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

    cout << "Enter second number: ";
    cin >> num2; 

    cout << "Enter third number: ";
    cin >> num3; 

    // Logic to find the largest number
    if (num1 >= num2 && num1 >= num3) { 
        cout << "The largest number is: " << num1 << endl;
    }
    else if (num2 >= num1 && num2 >= num3) { 
        cout << "The largest number is: " << num2 << endl;
    }
    else { 
        // If the above are false, num3 must be the largest
        cout << "The largest number is: " << num3 << endl;
    }

    return 0; // Program executed successfully
}

Console Output:

Enter first number: 12
Enter second number: 45
Enter third number: 23
The largest number is: 45
Flow Control & Logic
Find the Largest of Three Numbers in C++ Relational Operators and Logical AND in C++ If-Else If Branching and Decision Making Basic C++ Comparison Algorithms

Share this C++ Exercise

Help others learn conditional logic and comparisons in C++.

© C++ Programming Exercises. Master the art of performance coding.