C programming recursion

In this tutorial, you will learn about c programming recursion with the examples of recursive functions.

C programming recursive functions

Until now, we have used multiple functions that call each other but in some case, it is useful to have functions that call themselves. In C, such function which calls itself is called recursive function and the process is called recursion.

For example:

main ()
{
printf("Recursion \n");
main();
}

In this above example, main function is again called from inside the main function. So this function will keep on printing Recursion until the program run out of memory.

Example of recursive function: C program to find the factorial of first 3 natural numbers using recursion

First of all, the recursive factorial function checks whether if condition is true or not i.e whether n is less than or equal to 1. If condition is true, factorial returns 1 and the program terminates otherwise the following statement executes.

return ( n * fact (n-1) );

Common Programming Errors

Forgetting the base case or incorrect recursion step that does not converge will cause infinite recursion.