# C Programming – How Recursion Function Works with Example of Factorial

Basically, a function is said to be recursive if it calls itself. Recursion is a good problem solving approach solve a problem by reducing the problem to smaller sub problems.

A recursive function has to be invoked for the first time from outside function definition however it keeps calling itself from inside function definition until it reaches a terminating condition.

## How Recursion works ?

int fact(int n) { if(n==1) { return 1; } else { return n * fact(n-1); //call repeatedly with modified parameter i.e recursive call } } int main() { int result= fact(5); //first time call from main printf("\n\t FACTORIAL: %d",result); return 0; }

Every recursive function has two part, first is terminating condition and second function call itself with modified parameter value. if terminating condition is wrong or not met, execution of code goes into infinite loop.

**step 1**: fact function with parameter value n as 5 is called from main function as `result = fact(5)`

**step 2**: In `fact(5)`

function , the terminating condition is `n==1`

, Here value of n is 5 , so place call as `n*fact(n-1)`

which is `5*fact(4)`

**step 3**: In `fact(4)`

function , Here value of n is **4** , so place call as `n*fact(n-1)`

which is `4*fact(3)`

**step 4**: In `fact(3)`

function , Here value of n is **3** , so place call as `n*fact(n-1)`

which is `3*fact(2)`

**step 5**: In `fact(2)`

function , Here value of n is **2** , so place call as `n*fact(n-1)`

which is `2*fact(1)`

**step 6**: In `fact(1)`

function , Here value of n is **1** , so terminating condition `(n==1)`

is satisfied, hence it return value 1 as a result to its previous function `fact(2)`

where it get called.

**step 7**: In `fact(2)`

function , it returns a value `2*fact(1)`

as 2*1 which is **2** as a result to its previous function `fact(3)`

**step 8**: In `fact(3)`

function , it returns a value `3*fact(2)`

as 3*2 which is **6** as a result to its previous function `fact(4)`

**step 9**: In `fact(4)`

function , it returns a value `4*fact(3)`

as 4*6 which is **24** as a result to its previous function `fact(5)`

**step 10**: In `fact(5)`

function , it returns a value `5*fact(4)`

as 5*24 which is **120** as a result to its previous function `main`

**step 11**: In main function , 120 value get assigned to result variable.

###### DOWNLOAD fact-function-using-recursion.c (57 downloads)

###### OUTPUT