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

Howdy readers, today you will learn how to write a C++ program to find the largest of three numbers using functions.

The below program prompts the user to enter three numbers, then it computes the largest among them using a user-defined function.

The user-defined function uses comparison operators to find the largest number in the below program.

So, without any delay, let’s begin this tutorial.

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

C++ Program

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

// User-defined function
int largestNumber(int a, int b, int c){
    int max;
    if (a >= b && a >= c){
        max = a;
    }
    else if (b >= a && b >= c){
        max = b;
    }
    else{
        max = c;
    }
    return max;
}

int main(){
    int num1, num2, num3, largest;
    
    // Taking input
    cout << "Enter the first number: ";
    cin >> num1;
    cout << "Enter the second number: ";
    cin >> num2;
    cout << "Enter the third number: ";
    cin >> num3;
    
    // Calling out function
    largest = largestNumber(num1, num2, num3);
    
    // Display result
    cout << "Largest number is: " << largest << endl;
    
    return 0;
}

Output

Enter the first number: 18
Enter the second number: 30
Enter the third number: 27
Largest number is: 30
C++ Program to Find Largest of Three Numbers Using Functions

Explanation

int largestNumber(int a, int b, int c){
    int max;
    if (a >= b && a >= c){
        max = a;
    }
    else if (b >= a && b >= c){
        max = b;
    }
    else{
        max = c;
    }
    return max;
}

In this program, we have defined a function named largestNumber which passes three numbers as arguments and returns the greatest of them.

    // Calling out function
    largest = largestNumber(num1, num2, num3);

Then, we call out the custom function in the main function. This gives us the desired result. We store the largest number in the largest named variable.

    cout << "Largest number is: " << largest << endl;

The largest number among the three is displayed on the screen using the cout statement.

Conclusion

Today you learned how to write a C++ program to find the largest of three numbers using a function.

If you have any doubts regarding the tutorial, comment down your queries in the comment section.

Thanks for reading.

Happy Coding!!

Also Read:

Leave a Comment