Recursive Functions is the process of defining something in terms of itself. It is a function that calls itself again in the body of the function.
A function fact ( ), that computes the factorial of an integer ‘N’ ,which is the product of all whole numbers from 1 to N.
When fact ( ) is called with an argument of 1 (or) 0, the function returns 1. Otherwise, it returns the product of n*fact (n-1), this happens until ‘n’ equals 1.
Fact (5) =5* fact (4) =5*4*3* fact (3) =5*4*3*2* fact (2) =5*4*3*2*1 fact (1) =5*4*3*2*1 = 120.
Example
Following is the C program for recursive function −
#include<stdio.h> int main ( ){ int n,f; int fact (int); printf ("enter a number"); scanf ("%d", &n); f= fact (n); printf ("factorial value = %d",f); } int fact (int n){ int f; if ( ( n==1) || (n==0)) return 1; else f= n*fact (n-1); return f; }
Output
When the above program is executed, it produces the following result −
Enter a number 5 Factorial value = 120