Adsense 728 * 15

Search

Custom Search

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

Write a c++ program to print factorial of a number using recursion. In this programming question, we are going to write a c++ code which takes an input number and print factorial of a number using recursion.

This question is mostly asked in an interviews. There are two approaches to print factorial of a number (Iterative & Recursive).

i) C++ program to print factorial of a number - Iterative approach

ii) Second approach is to print factorial of a number using recursion. In this tutorial, we are going to discuss second approach.

C program to print factorial of a number

Java program to print factorial of a number

C program to print factorial of a number using recursion

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



Let's write our code.

i)  First, take an input number from a user.
ii) Then call a method which recursively prints the factorial of a number.


#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 a number \n";
   cin  >> num;
 
   fact = calculateFactorial (num);
 
   cout << "Factorial of a number " << num << " is " << fact;
 
   return 0;
}


Output :

Enter a number : 4

Factorial of a number  4 is 24

Explanation : Suppose we have entered 4 so how this program is going to be executed.

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

No comments:

Post a Comment