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
C Functions
C Function Arguments and Return Value
C Call by Value and Call by Reference
C Recursion
C Scope and Storage Classes
Exercises & Assignments
Write a C program to find the factorial of a number using recursion
Write a C program to swap two numbers using a function and pointers
Interview Questions & Answers
What is the difference between call by value and call by reference in C?
What is recursion in C?
What is the difference between local and global variables in C?
What are storage classes in C?
What is the use of the static keyword in C?