Recursion functions

When a calling function, in turn, another function is called a 'chaining' process recursion occurs in a special case of this process, where a function calls itself. A very common example of recursion is presented below:

int main()
 printf("This is an example\n");
 return 0;
factorial(int n)
 int fact;
 fact = n*factorial(n-1);

Let us see how the recursion works. Assum n =3. Since the value of n is not 1. the statement

fact = n * factorial(n-1);

will be executed with n = 3. That is,

fact = 3 * factorial(2);

will be evaluated. The expression on the right-hand side includes a call to factorial with n=2. This call will return the following value :

2 * factorial(1)

Once again, factorial is called with n = 1. This time, the function returns 1. The sequences of operations can be summarized as follows :

fact = 3 * factorial(2)
     = 3 * 2 * factorial(1)
     = 3 * 2 * 1
     = 6

Recursive functions can be effectively used to solve problems where the solution is expressed in the case of applying the same solution continuously to the problem subsets. When we write recursive functions, we must have a statement somewhere to force the function to return without executing the repeated call. Otherwise, the function will never return.