Write a C program to find the factorial of a number using recursion

Description: Write a recursive function to find the factorial of a number taken as input.

Hint:

  • n! = n x (n - 1)! and 0! = 1. The second rule is the base case.

C program for factorial using recursion

#include <stdio.h>

unsigned long long factorial(int n) {
    if (n <= 1) {
        return 1;                    // base case
    }
    return n * factorial(n - 1);     // recursive call
}

int main(void) {
    int n;

    printf("Enter a number: ");
    scanf("%d", &n);

    printf("Factorial of %d = %llu\n", n, factorial(n));
    return 0;
}

Output:

Output of the above program is

Enter a number: 6
Factorial of 6 = 720

How it works

  • factorial(6) calls factorial(5), and so on, until factorial(1) returns 1.
  • Then the answers are multiplied while the calls return: 1, 2, 6, 24, 120 and 720.

Read C Recursion.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.