A function call itself in its body is called recursive function. A recursive function can be used instead of a loop control. Hence, programmer should take care to avoid infinite loop.
/*program to find factorial of a number-without recursion*/
#include
main ()
{
int n, factorial; //declaration of variables
int fact(int); //declaration of fact function
printf (“Enter any number:\n” );
scanf (“%d”, &n);
factorial = fact (n);
printf (“Factorial is %d\n”, factorial);
}
/* Non recursive function of factorial */
int fact (int n) //formal argument
{
int res = 1, i;
for (i = n; i >= 1; i–)
res = res * i;
return (res);
}
/*Program to find factorial using recursion*/
#include
main()
{
int n, factorial;
int fact(int);
printf(“Enter any number: \n” );
scanf(“%d”,&n);
factorial = fact(n); /*Function call */
printf (“Factorial is %d\n”, factorial); }
/* Recursive function of factorial */
int fact(int n)
{
int res;
if(n == 1) /* Terminating condition */
return(1);
else
res = n*fact(n-1); /* Recursive call */
return(res); }