Adsense 728 * 15

Search

Custom Search

Find Factorial of a Number using Recursion in C, C++

Write a C, C++ program to find factorial of a number using recursion.  How do i write a factorial program in C, C++ using recursion concept.

In my previous i have explained how to find factorial of a number using iterative approach. In this post i'll explain how to find factorial of a number using recursion. If you are not familiar with recursion concept then read this tutorial on Recursion vs Iteration.


MCQ on Recursion for Practice.

C Program to Find Factorial of a Number using Recursion


#include <stdio.h>

int calculateFactorial (int num) {
 
  /* If number is zero or 1 then return 1 */

  if ( num == 0 || num == 1) {
   
     return 1;
   
   } 
  
   /* Recursive function call */

   return num * calculateFactorial(num-1);;
}

int main(void) {
 
  int num, fact = 0;
 
  printf ("Enter number \n");
  scanf ("%d", &num);
 
  /* Function call */

  fact = calculateFactorial(num);
 
  printf ("Factorial of a number %d is %d ",num,fact);
  return 0;
}


Output :

Enter number :  5

Factorial of a number 5 is 120


C++ Program to Find Factorial of a Number using Recursion


#include <iostream>
using namespace std;

int calculateFactorial (int num) {
 
  if ( num == 0 || num == 1) {
   
     return 1;
   
   } 
  
   return num * calculateFactorial(num-1);;
}


int main() {
 
   int num, fact = 0;
 
   cout << "Enter number \n";
   cin >> num;
 
   fact = calculateFactorial (num);
 
   cout << "Factorial of a number " <<num << " is " << fact;
 
   return 0;
}

Explanation :

Suppose you have entered 5 so how this program is going to be executed.

5 * calculateFactorial (5-1)
5 * 4 * calculateFactorial (4-1)
5 * 4 * 3 * calculateFactorial (3-1)
5 * 4 * 3 * 2 * calculateFactorial (2-1)
5 * 4 * 3 * 2 * 1 

No comments:

Post a Comment