Find factorial of a number using recursion | Factorial using recursion

In this tutorial, we will learn how to find factorial of a number by using recursion. If you want to learn how to find factorial of a number iteratively then read here.

Learn about recursion here.


Factorial :-

c program to find factorial of a number
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:-

  1. Start
  2. Take input number n from the user.
  3. call the function factorial and pass n as its parameter.
  4. Inside the factorial function call the factorial function and pass n-1 as its parameter and the return type of the function is int.
  5. Set the base case if n == 1 return 1, as it cannot go below the value of one.
  6. Finally return n * n-1.
  7. Print the result on the screen.
  8. 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

Post a Comment

0 Comments