C++ Program to Find Largest of Three Numbers

In the previous article, we have discussed C++ Program to Check Whether a Character is Vowel or Consonant. In this article, we will see C++ Program to Find Largest of Three Numbers.

C++ Program to Find Largest of Three Numbers

  • Write a C++ program to find maximum of three numbers using if-else statement.
  • How to find largest of three numbers using conditional operator.

First of all, we have to take three numbers as input from user and compares them to find the maximum of all three numbers.

C++ program to find maximum of three numbers using if else statement

In this program, we first finds largest of first two numbers and then compares it with third number.
C++ program to find maximum of three numbers using if else statement

#include <iostream>  
 
using namespace std;
 
int main()  {  
    int a, b, c, max;  
    /* 
     * Take three numbers as input from user 
     */
    cout <<"Enter Three Integers\n";  
    cin >> a >> b >> c;  
      
    if(a > b){
        // compare a and c
        if(a > c)
            max = a;
        else
            max = c;
    } else {
        // compare b and c
        if(b > c)
            max = b;
        else
            max = c;
    }
    
    /* Print Maximum Number */
    cout << "Maximum Number is = " << max;  
    
    return 0;  
}

Output

Enter Three Integers
8 2 6
Maximum Number is =  8

C++ Program to find maximum of three numbers using conditional or ternary operator

Let A, B and C are three input numbers. We first find largest of A and B. Lets say A > B then we will compare A and C to find the largest of all three numbers. We are going to use conditional operator here, which is similar to IF-THEN-ELSE statement.
C++ Program to find maximum of three numbers using conditional or ternary operator

#include <iostream>
 
using namespace std;  
    
int main()  {  
    int a, b, c, max;  
    /* 
     * Take three numbers as input from user 
     */
    cout << "Enter Three Integers\n";  
    cin >> a >> b >> c;  
      
    max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
    
    /* Print Maximum Number */
    cout << "Maximum Number is = " << max;  
    
    return 0;  
}

Output

Enter Three Integers
7 12 9
Maximum Number is = 12

The popular Examples of C++ Code are programs to print Hello World or Welcome Note, addition of numbers, finding prime number and so on. Get the coding logic and ways to write and execute those programs.