C++ Program to Find Largest of Two Numbers

In this post, we will learn how to find the largest of two numbers using C++ Programming language.

We will find the largest of two numbers using If. . .Else statement.

So, without further ado, let’s begin this tutorial.

C++ Program to Find Largest of Two Numbers

// C++ Program to Find Largest of Two Numbers
#include <iostream>
using namespace std;

int main(){
    int x, y;
    
    // Asking for input
    cout << "Enter the first number: ";
    cin >> x;
    cout << "Enter the second number: ";
    cin >> y;
    
    if (x > y){
        cout << x << " is greater than " << y;
    }
    else if (y > x){
        cout << y << " is greater than " << x;
    }
    else{
        cout << "Both are equal";
    }
    return 0;
}

Output 1

Enter the first number: 18
Enter the second number: 12
18 is greater than 12

Output 2

Enter the first number: 15
Enter the second number: 15
Both are equal

How Does This Program Work ?

    int x, y;

In this program, we have declared two int data type variables named x and y.

    // Asking for input
    cout << "Enter the first number: ";
    cin >> x;
    cout << "Enter the second number: ";
    cin >> y;

Then, the user is asked to enter the value of x and y.

    if (x > y){
        cout << x << " is greater than " << y;
    }

Now, we check whether x > y, then the first entered number is greater than the second one.

    else if (y > x){
        cout << y << " is greater than " << x;
    }

If y > x, then the second number is greater than the first number.

    else{
        cout << "Both are equal";
    }

If neither of the above statements are true, it means both numbers are equal.

C++ Program to Find Largest of Two Numbers Using Functions

// C++ Program to Find Largest of Two Numbers Using Function
#include <iostream>
using namespace std;

int largeroftwo(int x, int y){
    if (x > y){
        return x;
    }
    else if (y > x){
        return y;
    }
}

int main(){
    int x, y, larger;
    
    // Asking for input
    cout << "Enter the first number: ";
    cin >> x;
    cout << "Enter the second number: ";
    cin >> y;
    
    larger = largeroftwo(x, y);
    
    // Displaying output
    cout << larger << " is greatest";
    return 0;
}

Output

Enter the first number: 12
Enter the second number: 17
17 is greatest

Conclusion

I hope after going through this post, you understand how to find the largest of two numbers using C++ Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to solve your query.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *