Function Recursion in C - C Function

C examples for Function:Recursive Function

Introduction

C function can call itself.

A function that call itself is called recursive function.

The following code create a recursive function, which computes the factorial of an integer.

The factorial of a number n is the product of all the whole numbers between 1 and n.

For example, 3 factorial is 1 * 2 * 3, or 6.

Demo Code

#include<stdio.h>

int factr(int n) {
   int answer;// w  ww .j a v  a  2s . c  om

   if (n == 1) 
      return(1);
   answer = factr(n - 1)*n; /* recursive call */
   return(answer);
}

/* non-recursive */
int fact(int n) {
   int t, answer;

   answer = 1;
   for (t = 1; t <= n; t++)
      answer = answer*(t);

   return(answer);
}

int main(void)
{

   printf("%d \n", fact(8));
   printf("%d", factr(8));
   return 0;
}

Related Tutorials