C - Function Function Recursion


A function which calls itself is termed as recursion.

The following code does calculation of the factorial of an integer.

A factorial of any integer is the product of all the integers from one up to the integer itself.


#include <stdio.h>

unsigned long long factorial(unsigned long long);

int main(void)
  unsigned long long number = 10LL;
  printf("The factorial of %llu is %llu\n", number, factorial(number));
  return 0;/* w w  w.  j a  v  a  2s  .  com*/

// A recursive factorial function
unsigned long long factorial(unsigned long long n)
  if (n < 2LL)
    return n;

  return n * factorial(n - 1LL);


factorial() function gets called from main() with number 10.

Within the factorial() function itself, this statement is executed:

return n*factorial(n - 1LL);

It calls factorial() again with the argument value 9.

This expression can't be evaluated, until the value is returned from the call to the function factorial() with the argument 9.

This continues until the argument in the last call of the factorial() function is 1.

In this case, the first return statement is executed:

This returns the value 1 to the previous call point.

Related Topics