How to use if-else Statement In C++
In this method, we will use the if-else ladder to check each of the numbers for the largest using compound relational expressions. If after checking three numbers, there is no largest, then we can be sure that the last number will be largest.
Algorithm
- Compare a with b, c and d. If a is greatest, print a.
- Else compare b with a, c and d. If b is greatest, print b.
- Else compare c with a, b and d. If c is greatest, print c.
- Else d is greatest, print d.
Program to Check Largest Number among Four Number using if-else
C++
// C++ program to find the largest number usign if else #include <iostream> using namespace std; int main() { // defining four numbers int a = 1, b = 2, c = 4, d = 3; // checking if a is largest if (a >= b && a >= c && a >= d) cout << "Largest Number: " << a; // checking if b is largest else if (b >= a && b >= c && b >= d) cout << "Largest Number: " << b; // checking if c is largest else if (c >= a && c >= b && c >= d) cout << "Largest Number: " << c; // d is largest else cout << "Largest Number: " << d; return 0; } |
Largest Number: 4
C++ Program to Find Largest Among Four Numbers
In this article, we will see how to find the largest among four numbers in a C++ program.
Examples:
Input: a = 1, b = 2, c = 4, d = 3
Output: 4
Input: a = 0, b = -1, c = -3, d = -2
Output: 0