OverIQ.com

C Program to calculate Factorial using recursion

Last updated on September 24, 2020


The following is a C Program to calculate Factorial using recursion:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**************************************************
 Program to calculate Factorial using recursion 
 * 
 * Enter a number: 4
 * 4! = 24
 ***************************************************/

#include<stdio.h> // include stdio.h library
long factorial(int num);

int main(void)
{    
    int n;

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

    printf("%d! = %ld", n, factorial(n));

    return 0; // return 0 to operating system
}

long factorial(int num)
{    

    //base condition
    if(num == 0)
    {
        return 1;
    }

    else
    {
        // recursive call
        return num * factorial(num -  1);
    }

}

Try it now

Expected Output:

1st run:

1
2
Enter a number: 0
0! = 1

2nd run:

1
2
Enter a number: 5
5! = 120

How it works #

The following figure demonstrates how the evaluation of 5! takes place:

Recursion in action