Table of Contents
Introduction
In this program, you will learn to calculate the factorial of a number entered by the user using the process of recursion.
The factorial of a positive integer ‘x’ is 1*2*3*4*……..*x.
For example, Factorial of 5 is (! is the symbol for factorial):
5! =5*4*3*2*1=120
Similarly, Factorial of 7 is
7! =7*6*5*4*3*2*1=5040
Factorial of negative numbers doesn’t exist.
Factorial of 0 and 1 is 1.
What is the use of this program?
It is easy to calculate the factorial up to certain values but it is difficult to calculate factorial like 100! , 500! etc. A small code written in C++ will make this task quite easy.
To understand this example, you should know about the following C++ programming topics:
1. Data types
2. Operators
3. Recursion
4. User-defined functions
Recursion is the process in which a function calls itself.
Program
#include<iostream> using namespace std; int factorial (int x) { if(x==0) { return 1; } else { return x*factorial(x-1); // recursive call } } int main() { int n; cout<<"Enter a positive integer: "; cin>>n; int fact=1; // fact to store the factorial if(n>=0) // if n is positive integer { fact=factorial(n); cout<<"Factorial of "<<n<<" is "<<fact; } else // if n is negative integer { cout<<"factorial doesn't exist"; } return 0; }
Output
Explanation
In the above program, we have to calculate the factorial of ‘n’.
The user is asked to enter the value of ‘n’.
If ‘n’ is a positive number only, then we will proceed with the ‘factorial’ function else, ‘n’ is a negative number, and the statement “factorial doesn’t exist” gets printed.
factorial is a user-defined function declared with ‘int’ type, and ‘x’ is passed as an argument in it.
Now, we have only two options.
Either ‘x’ is 0 for that factorial will be 1
Or ‘x’ is greater than 0, and for that recursion, the process will take place.
return x*factorial(x-1);
factorial function calls itself with decreasing values of ‘x’ each time.
0 Comments