Largest Among 3

Program to find the largest of three numbers

C++Beginner
C++
#include <iostream>
using namespace std;

int main() {
    int a, b, c, largest;
    
    cout << "Enter three numbers: ";
    cin >> a >> b >> c;
    
    if (a >= b && a >= c) {
        largest = a;
    } else if (b >= a && b >= c) {
        largest = b;
    } else {
        largest = c;
    }
    
    cout << "Largest number is: " << largest << endl;
    
    return 0;
}

Output

Enter three numbers: 10 25 15
Largest number is: 25

Largest Among Three Numbers in C++

This program teaches how to find the largest number among three given numbers using conditional statements. This is a fundamental problem-solving skill that helps students understand comparison logic, nested conditions, and logical operators in C++.

Program Logic

The program uses nested if-else statements to compare the three numbers:

cpp
if (a >= b && a >= c) {
    largest = a;
} else if (b >= a && b >= c) {
    largest = b;
} else {
    largest = c;
}

Understanding the Conditions

First condition: a >= b && a >= c

  • Checks if a is greater than or equal to b ## AND greater than or equal to c
  • If both conditions are true, then a is the largest
  • The && operator means "both conditions must be true"

Second condition: b >= a && b >= c

  • Checks if b is greater than or equal to a ## AND greater than or equal to c
  • If both are true, then b is the largest

Else case:

  • If neither a nor b is the largest, then c must be the largest
  • This is why we use else without a condition

Why Use >= Instead of >?

We use >= (greater than or equal) instead of > (greater than) to handle cases where two or more numbers are equal.

Example:

  • If input is: ## 10, 10, 5
  • Using >= correctly identifies that both 10s are the largest
  • Using > might miss this case

Summary

  • The program compares three numbers using nested if-else statements
  • Logical AND (&&) operator checks multiple conditions simultaneously
  • Using >= handles cases where numbers might be equal
  • This is a fundamental pattern for finding maximum/minimum values
  • Understanding this logic helps in solving more complex comparison problems

This program is essential for beginners as it teaches conditional logic, which is used in almost every real-world program. Once you master this, you can easily extend it to find the largest among more numbers or find the smallest number.