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:
cppif (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
ais greater than or equal tob## AND greater than or equal toc - If both conditions are true, then
ais the largest - The
&&operator means "both conditions must be true"
Second condition: b >= a && b >= c
- Checks if
bis greater than or equal toa## AND greater than or equal toc - If both are true, then
bis the largest
Else case:
- If neither
anorbis the largest, thencmust be the largest - This is why we use
elsewithout 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.