C++ program to find factorial of a number

C++ Program to find factorial of a number

In this article, we will discuss another basic and one of the important programs of c++ - "factorial of a number". Before going further, let's understand what a factorial is. Factorial of a number 'x' is a product of all the positive integers up to 'x'. For example, the factorial of 5 is 5*4*3*2*1 = 120.

So here we will discuss factorial using :

1. For loop, and
2. Recursion

1. Using for loop:-

First, we will compute the factorial using for loop. So Given below is the code to find factorial of a number:-

#include<iostream>
using namespace std;
int main()
{
int n,fact=1;
cout<<" Enter the number : ";
cin>>n;
if (n < 0) cout << "Error! Factorial doesn't exist.";
else {
for (int a=1;a<=n;a++)
fact=fact*a;
}
cout<<"\n Factorial is = "<<factorial<<endl;
return 0;
}
OUTPUT:-
Enter the number: 5
Factorial is 120
In this above program, we take the positive integer by the user and store it in n variable. Now we check what the user enters a positive integer or negative integer. If the user enters a negative integer we print an error message else we compute the factorial of the number and print it.

2. Using recursion:-

Now, we will compute the factorial using recursion. So Given below is the code to find factorial of a number:

#include<iostream>
using namespace std;
int fact(int n){
    if(n==1) return 1;
    else return n*fact(n-1);
}
int main(){
    int n;
    cout<<"\nEnter the number ";
    cin>>n;
    cout<<"\nFactorial of the number is :: "<<fact(n);
    return 0;
}
OUTPUT:-
Enter the number: 5
Factorial is 120

Post a Comment

0 Comments