C++ Program to Find Factorial of a Number Using Function

Howdy readers, today you will learn how to write a program to find the factorial of a number using a function in C++ Programming language.

C++ Program to Find Factorial of a Number Using Function

The below program prompts the user to enter an positive integer, then it computes the factorial of the entered number using a user-defined function.

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

C++ Program to Find Factorial of a Number Using Function

C++ Program

// C++ Program to Find Factorial of a Number Using Function
#include <iostream>
using namespace std;

int findFact(int);

int main(){
    int num, factorial;
    
    // Taking input from the user
    cout << "Enter an integer: ";
    cin >> num;
    
    // Calling out function
    factorial = findFact(num);
    
    // Displaying result
    cout << "Factorial of " << num << " is: " << factorial << endl;
    
    return 0;
}

int findFact(int n){
    int i, f = 1;
    
    for (i = 1; i <= n; i++){
        f = f * i;
    }
        
    return f;
}

Output

Enter an integer: 4
Factorial of 4 is: 24
C++ Program to Find Factorial of a Number Using Function

Explanation

    int num, factorial;

In this program, we have declared two int data type variables named num and factorial.

    // Taking input from the user
    cout << "Enter an integer: ";
    cin >> num;

The user is asked to enter a positive integer. This gets stored in the num named variable.

    // Calling out function
    factorial = findFact(num);

Now, we call the custom function named findFact which we have defined earlier. This gives us the factorial of the entered number.

int findFact(int n){
    int i, f = 1;
    
    for (i = 1; i <= n; i++){
        f = f * i;
    }
        
    return f;
}

Here, we have defined a custom function named findFact() which computes and returns the factorial of any number using a for loop.

The value of the factorial computed using the function gets stored in the factorial named variable.

    // Displaying result
    cout << "Factorial of " << num << " is: " << factorial << endl;

Finally, the factorial of the entered number is displayed on the screen using the cout statement.

Conclusion

I hope after reading this post, you understand how to write a program to find the factorial of a number using a function in C++ Programming language.

If you have any queries regarding the tutorial, then let us know in the comment section. We will be pleased to solve all of your queries.

Leave a Comment