Factorial of a positive number is a number which is obtained by multiplying all sequence of number starting with 1 till the number itself. Thus factorial calculation is a repititive process and recursion is often used for this.

unsigned int factorial(unsigned int n )
{
  if ( n <= 1 )
  {
    return 1;
  }
  else
  {
    return n * factorial(n - 1);/*Call itself*/
  }
}

factorial can also be done using normal loop based logics. Below is non-recursive code sniffet.

unsigned int factorial(unsigned int n )
{
  int result = 1;
  for (i = n; i > 1; i--)
  {
    result = result * i;
  }
  return result;
}

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

macro vs inline-function, function pointer, default C++ argument value, Recursion, factorial using recursion, Fibonaci using recursion, Armstrong number, variadic functions,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan