**Summary**: in this tutorial, you will learn about the **C recursive function**, which is a function that calls itself.

## C recursive function definition

A recursive function is a special function that calls to itself. Like other programming languages, C allows you to define recursive functions easily.

## Why recursive function

A recursive function allows you to break down a complex problem into identical sub-problems recursively until the sub-problems are simple enough to solve directly. The solutions are then combined to produce the solution to the original problem. This is a famous programming technique called divide and conquer.

## Notes of using recursive function

A recursive function must have at least one exit condition that must be satisfied. Otherwise, the recursive function will call itself indefinitely until a stack overflow error occurs.

## C recursive function example

A recursive function is closely related to a definition of the function in mathematics. For example, the factorial number of a positive integer `N`

is calculated by the following formula:

`N! = N*(N-1)*(N-2)…2*1;`

Or defined by using a recursive function:

`N! = 1 if N <=1 and N! = N*(N-1)! if N > 1`

The C recursive function to calculate the factorial of a positive integer `N`

is as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <stdio.h> int factorial(unsigned int number); void main() { int n; printf("Please enter a positive integer to calculate its factorial:"); scanf("%d",&n); printf("factorial of %d is %d",n,factorial(n)); } int factorial(unsigned int n) { if(n <= 1) { return 1; } return n * factorial(n - 1); } |

How it works.

- Calculate the factorial of n via factorial of n-1 recursively until n is equal to 1.
- If n is less than or equal to 1, the factorial of n is 1.

The output of the program when you enter 4 to calculate its factorial number is:

1 2 | Please enter a positive integer to calculate its factorial:4 factorial of 4 is 24 |

In theory, all recursive functions can be rewritten by a loop statement such as while loop, do while loop or for loop. In case the number of recursive calls exceeds, a stack overflow error occurs. In this situation, you have to re-implement the recursive function by using a loop statement.

For example, we can rewrite the factorial calculation function that uses the `while `

loop statement as follows:

1 2 3 4 5 6 7 | int factorial(unsigned int n) { int f = 1; while(n > 0) f *= n--; return f; } |

Recursion technique is applied in many algorithms e.g., it is implemented in the quicksort algorithm and binary search algorithm.

In this tutorial, we’ve shown you how to use recursive functions. The recursion technique can be effective if you apply it appropriately.