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

  1. Compare a with b, c and d. If a is greatest, print a.
  2. Else compare b with a, c and d. If b is greatest, print b.
  3. Else compare c with a, b and d. If c is greatest, print c.
  4. 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;
}


Output

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

Similar Reads

Methods to Find the Largest of Four Numbers

There are 4 ways to find the largest among the four numbers in C++:-...

1. Using if-else Statement

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....

2. Using Nested if-else

...

3. Using Ternary Operator

In this approach, instead of checking each number using compound expressions, we will compare two numbers, and if one is greater, then inside that if statement, we will compare this number with another number. We will keep nesting if-statements till the number is compared with all the other numbers....

4. Using In-built std::max() Function

...