Recursion in C :

When a function call itself repeatedly, until some specified condition is met, then this process is called recursion. It is useful for writing repetitive problems where each action is stated in terms of previous result. The need of recursion arises if logic of the program is such that the solution of the problem depends upon the repetition of certain set of statements with different input values and end with a condition.

There are two basic requirement for recursion.

1. The function must call itself again and again.

2. It must have a stopping condition.

To understand the concept of recursion, let us consider an example where we need to calculate the factorial of a number recursively. The factorial of 0 and 1 and factorial of any positive integer n is the product of n and factorial of the number (n-1).

Therefore, 0!=1

n!=n*(n-1)!, n>0

Now the question arises what is the factorial of (n-1) . It is infact , the product of (n-1) and factorial of (n-2). This process continues till n becomes 0. In which case , factorial is 1. So the result obtained from 0! (i.e. 1) is then used to compute 1! and the result of 1! is used to compute 2! and this process is repeated until we compute n! .

Advantages of recursion:

It makes the program code compact which is easier to write and understand. It is suitable to be used with data structures such as linked lists, stack etc. Recursion is useful if a solution to a problem is in repetitive form factorial(n)=n*factorial(n-1)

4.The compact code in recursion simplifies the compilation as less numbers of lines need to be compiled. 4.The compact code in recursion simplifies the compilation as less numbers of lines need to be compiled.





Disadvantages of recursion: