Signup/Sign In

C++ Program To Find Greatest Among Three Numbers

In this tutorial, we will learn how to find the greatest number among three numbers given by the user The largest number among three numbers can be found using the if statement multiple times.

Program To Find Greatest Among Three Numbers In C++

#include<bits/stdc++.h>
using namespace std;

int greatest(int a,int b,int c){
    if(a>b&&a>c){
        return a;
    }
    else if(b>a&&b>c){
        return b;
    }
    else{
        return c;
    }
}

int main(){
    int num1,num2,num3;
    cout<<"Enter the three numbers:-";
    cin>>num1>>num2>>num3;
    cout<<greatest(num1,num2,num3);
    return 0;
}

In the above program, firstly, a is compared to b. If a is greater than b, then it is compared to c. If it is greater than c as well, that means a is the largest number and if not, then c is the largest number.

if(a>b) {
   if(a>c)
   cout<<a<<" is largest number";
   else
   cout<<c<<" is largest number";
}

If a is not greater than b, that means b is greater than a. Then b is compared to c. If it is greater than c, that means b is the largest number and if not, then c is the largest number.

else {
   if(b>c)
   cout<<b<<" is largest number";
   else
   cout<<c<<" is largest number";
}

Enter the three numbers:-
5 3 9

9

Conclusion

Here, we have learned how to implement if-else statements to find the largest of three numbers.