Learn about recursion here.
Factorial :-
Factorial of number |
A factorial of any positive number 'n' is given by
n! = 1 * 2 * 3 * 4 * . . . . * n;
Factorial is denoted by exclamation mark ( ! ) and the negative numbers cannot have factorial.Let's see few examples of factorial
1. if n = 5 then
5! = 1 * 2 * 3 * 4 * 5 = 120.
2. if n = 12 then
7! = 1 * 2 * . . . * 7 = 5040.
Algorithm to find factorial of a number using recursion:-
- Start
- Take input number n from the user.
- call the function factorial and pass n as its parameter.
- Inside the factorial function call the factorial function and pass n-1 as its parameter and the return type of the function is int.
- Set the base case if n == 1 return 1, as it cannot go below the value of one.
- Finally return n * n-1.
- Print the result on the screen.
- Stop.
Program :-
#include <stdio.h>
// function to find factorial of a number using recursion
// Note the return of this function is integer.
int factorial(int n) {
if(n==1) { // Base case
return 1;
}
int f = factorial(n-1);
return n * f;
}
int main()
{
int n;
printf("Enter a number: \n");
scanf("%d", &n); // input the number n from the user
int result = factorial(n); // call the facctorial function
// and store the return value in the result variable
printf("The factorial of %d is : %d", n, result);
return 0;
}
Output:-
Enter a number:
7
The factorial of 7 is : 5040
Enter a number:
5
The factorial of 5 is : 120
Instead of calling the function and storing the value in a temporary variable we can also call the function and directly multiply with the value n as shown in the below program.
Program :-
#include <stdio.h>
// function to find factorial of a number using recursion
// Note the return of this function is integer.
int factorial(int n) {
if(n==1) { // Base case
return 1;
}
return n * factorial(n-1);
}
int main()
{
int n;
printf("Enter a number: \n");
scanf("%d", &n); // input the number n from the user
int result = factorial(n);
printf("The factorial of %d is : %d", n, result);
return 0;
}
Output:-
Enter a number:
5
The factorial of 5 is : 120
0 Comments