This article is a program to find factorial in C language using recursive function. Before going straight to the code, let’s talk about Recursive functions and what are they?
Recursive function is a tricky topic in C. They are the functions which calls themselves. So whenever you see a function which contains its own name that means its calling itself and hence it is recursive. They use Stack data structure to work.
There is a little something important about Recursive function which we should all remember while writing them, that is an if statement must be there. That means if I write a recursive function and it calls itself then there must be a point that it must stop calling itself or the loop must have a stopping statement, Because if it doesn’t then the function will call itself forever, going into an infinite loop.
Now, let’s get to the code,
CODE:
#include void main(){ int n; printf("Enter a number:"); scanf("%d",&n); if(n<0){ printf("Invalid number"); } else { printf("Factorial of %d is %d",n,fact(n));// fact(n) is used here } } //fact function int fact(int x) { //if statement to end the calling if(x == 0) { return 1; } else { //actual formula for recursion return(x*fact(x-1));//fact function is calling itself here and each time decreasing its value by 1 //until x == 0 then it will stop. } }
OUTPUT: