Write a C++ program that takes three integers/numbers as input and outputs the largest of the three.
Input and Output Examples
- Input: 5, 13, 2 Output: The largest number is 13.
- Input: -1, -3, -2 Output: The largest number is -1.
Algorithm
- Prompt the user to enter three integer numbers.
- Compare the first number with the second and third numbers, if it is the largest number, print that number.
- If not, check for the same with second and third number.
- Print the largest number.
Here is the C++ code that follows the above algorithm to find the largest number among the three input values.
#include <iostream>
using namespace std;
int main() {
int num1, num2, num3, largest;
// Step 1: Input three numbers from the user
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;
// Step 2 & 3: Compare the numbers and find the largest
if (num1 >= num2 && num1 >= num3) {
largest = num1;
} else if (num2 >= num1 && num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
// Step 4: Output the largest number
cout << "The largest number is " << largest << ".";
return 0;
}
Testing with Different Input Values
This program can handle any integers, whether positive, negative, or zero. Below are examples demonstrating its versatility:
Input and Output Examples for Modified Program:
- Input: 100, 25, 100 Output: The largest number is 100.
- Input: 0, 0, 0 Output: The largest number is 0.