C - Function Function Recursion

Introduction

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.

Demo

#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;/*from   www  .  jav a2s  .  c om*/
}

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

  return n * factorial(n - 1LL);
}

Result

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

Exercise