The mechanism
in which one function calls another function is known as Nesting Function.
The mechanism
in which a function calling itself is known as Recursion.
Recursion
can be explained using the concept of finding factorial of given number.
5! = 5 * 4!
= 5 * 4 * 3!
= 5 * 4 * 3 * 2!
= 5 * 4 * 3 * 2 * 1!
= 5 * 4 * 3 * 2 * 1
= 120
#include <stdio.h>
#include <conio.h>
void main ()
{
int n;
int factorial (int n);
clrscr ();
printf ("Enter Number:");
scanf ("%d", &n);
printf ("Factorial of %d is %d", n, factorial (n));
getch ();
}
int factorial (int n)
{
int fact;
if (n == 1)
return 1;
else
fact = n * factorial (n-1);
return fact;
}
Suppose the function is called using statement
factorial (5)
fact = 5 * factorial (4)
= 5 * 4 * factorial (3)
= 5 * 4 * 3 * factorial (2)
= 5 * 4 * 3 * 2 * 1
= 120
While using recursion if necessary care is not taken then execution of the program goes into the infinite loop. So necessary condition must be used to prevent program from going into the infinite loop.
Calling main () function from itself without specifying any condition will goes into the infinite loop. |