write a program to find the factorial of number using recursion



The code for this program is as follows:

#include<iostream.h>
#include<conio.h>
int fact(int number); //function declaration
int main()

{
int a,b;
cout <<"\nEnter number:";
cin>>a;
b=fact(a);//function calling
cout <<"\nfactorial of number is:"<<b;
getch();
return 0;

}

int fact(int number) //function definition

{
int f = 1;
if (number == 1)
{
return 1;
}
else
{
f= number * fact(number - 1); //recursion
}
return f;
}

In the above example, we have declared a fact(int number) to calculate the factorial of number.
In this program, we have declared two variables a for hold the user input value and b is used to hold the value which is returned by the function.
When function will call then a parameter will be passed to function. In the function, we have declared a variable f=1.
Now we are checking a condition to test if number is equal to 1 then it will return 1, if number is greater than 1 then else part will be executed. Inside else part, we have called the function again.
This function will execute till the number will not be equal to 1. When number will 1 then it will terminate and calculated values stored into the f variable as result. Then the function will return the factorial of given number and return to the calling place. At calling place, the value returned from the function will store in b variable.
The output of the above program is as follows:

Output

Enter number:5
factorial of number is:120