Recursive Functions


Those functions which are called by themselves are called Recursive functions. It means that the same function is called again within itself. The function itself becomes the calling function of it. Control is cycled within the function until a break point is reached in the program.

Non-Recursive Function

These functions are called only once from the calling function.
Eg:
/* Write C programs that use both recursive and non-recursive functions To find the factorial of a given integer.*/

#include< stdio.h>
#include< conio.h>
unsigned long factrec(int );
unsigned long factnrec(int );
void main()
{
 int a;
 unsigned long f1,f2;
 clrscr();
 printf("\n\n\t\tENTER VALUE OF A: ");
 scanf("%d",&a);
 f1=factrec(a);
 f2=factnrec(a);
 printf("\n\n\nFACTORIAL OF %d USING RECURSIVE FUNCTION IS: %d\n",a,f1);
 printf("\nFACTORIAL OF %d USING NON-RECURSIVE FUNCTION IS : %d",a,f2);
 getch();
}
/* RECURSIVE FUNCTION*/
 
unsigned long factrec(int x)
{
 if(x<=1)
  return 1;
 else
  return x*factrec(x-1);
}

/* NON-RECURSIVE FUNCTION*/
unsigned long factnrec(int x)
{
 int i;
 unsigned long f=1;
 if(x<=1)
  return 1;
 else
 {
  for(i = 1; i <= x; i++)
  	f=f*i;
 }
 return f;
}
								


OUTPUT:
ENTER VALUE OF A: 6
FACTORIAL OF 6 USING RECURSIVE FUNCTION IS: 720
FACTORIAL OF 6 USING NON-RECURSIVE FUNCTION IS : 720

Important Note:

  1. A function declared globally i.e, outside the main( ) function can be used by any other function in the program.
  2. Any C program contains atleast one function, which is nothing but the main( ).
  3. There is no limit on the number of functions that might be present in a C program.
  4. Each function in a program is called in the sequence specified by the function calls in main( ).
  5. A function can be called from another function, but a function cannot be defined in another function.
  6. Variables declared in the main( ) function and called functions are different. So, same Same variable names can be used in main( ) and called functions.