Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Recursively Calculating Factorials in C Programming

August 25, 2013 Posted by: GPA Views: 695 0 comments

Problem

Write program in C that calculates Factorial using recursive function.

Solution

For some problems, it is very useful to use functions that call themselves. Such functions are -recursive function. A recursive function is a function that calls itself. 

The factorial of a nonnegative integer n, written n! is the product:

n · (n –1) · (n – 2) · … · 1  

where 1!= 1, and 0! = 1. For example, 5! is the product 5 * 4 * 3 * 2 * 1, which is equal to 120.

The factorial of number, greater than or equal to 0 can be calculated without recursive function using a for statement as follows: 

int fact=1;//variable for product

for(int i=1;i<=somenumer;i++){

    fact*=i;//product of all number from 1 to somenumber example 5. Then output will be 120

In this lesson we discuss and write function factorial using recursive.

The recursive factorial function first check whether number is less than or equal to 1. If number is less than or equal to 1, factorial returns 1 and the program terminates. If number is greater than 1, use next statement

return number * factorial( number - 1 );  

 

Example:

   

#include <stdio.h>
#include <stdlib.h>
long factorial(long number);
long calculatefactorialnonrecursively(long number);
int main(int argc, char *argv[])
{
   int i;
   printf("Nonrecursively\n");
   for ( i = 0; i <= 10; i++ ) {
      printf( "%2d! = %ld\n", i,calculatefactorialnonrecursively(i));
   }
   printf("Using recursion\n");
   for ( i = 0; i <= 10; i++ ) {
     printf( "%2d! = %ld\n", i,factorial(i));
   }
   system("PAUSE");
   return 0;
}
//Nonrecursively
long calculatefactorialnonrecursively(long number){
   int fact=1;//variable for product
   int i;
   for(i=1;i<=number;i++){
      fact*=i;//product of all number from 1 to somenumber example 5. Then output will be 120
   }
  return fact;
}
//using recursion
long factorial(long number){
   if ( number <= 1 ) {
     return 1;
   }else{
      return ( number * factorial( number - 1 ));//call function factorial recursively
  }
}

 

Output

Recursively Calculating Factorials in C

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe