Recursion is a special case of function call where a function calls itself. These are very useful in the situations where solution can be expressed in terms of successively applying same operation to the subsets of the problem. For example, a recursive function to calculate factorial of a number n is given below:
Assume n=4, we call fact(4)
Since n≠1or 0, factorial=n*fact(n-1)
Factorial=4*fact(3) (again call fact function with n=3)
=4*3*fact(2) (again call fact function with n=2)
=4*3*2*fact(1) (again call fact function with n=1)
=4*3*2*1 (terminating condition)
=24
We should always have a terminating condition with a recursive function call otherwise function will never return.
A recursive program to reverse a string is:
printf("reverse of string is:\n");
rev(str);
getch();
}
rev (char *string)
{
if (*string)
{ rev(string+1);
putchar(*string);
}
}