In this tutorial program, we will write a program to find the largest of two numbers in C++. We will discuss few ways to do so. We will check two ways:
- Using if-else satement
- Using conditional operator.
To understand the program better, you should have knowledge of the following topics in C++.
C++ Program to Find Largest of Two Numbers using if else statement
The program takes a user input for the two numbers which are to be checked. Then using if else statement, t simply checks through the condition which one is greater and prints the result of the largest one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; int main() { int num1, num2; cout << "Enter the 1st number: "; cin >> num1; cout << "Enter the 2nd number: "; cin >> num2; if (num1 > num2) { cout << num1 << " is the largest."; } else { cout << num2 << " is the largest."; } return 0; } |
Outputs:
Enter the 1st number: 25
Enter the 2nd number: 30
30 is the largest.
C++ Program to Find Largest of Two Numbers using conditional operator
It is the same as the above, the difference is that instead of is else statement, we use the conditional operator. It works the same as the if else statement and makes the code clean and in a single line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream> using namespace std; int main() { int num1, num2, largest; cout << "Enter the 1st number: "; cin >> num1; cout << "Enter the 2nd number: "; cin >> num2; largest = (num1 > num2) ? num1 : num2; cout << largest << " is the largest of two."; return 0; } |
Outputs:
Enter the 1st number: 45
Enter the 2nd number: 13
45 is the largest of two.