-->





C++ program to find factorial using recursion

Write a program to find the Factorial using recursive function. User will enter a number and program should display result.

Concept  used:
  • Recursive function (returns number) int function(int n);
  • if-else statement    
  • Static variable

How program works
  • User enters a number which stores in variable 'num'
  • Then number passes as argument in function call
  •  A static variable is used to check that how many times function is called
  • When base case becomes true if(statement) then function returns result to main
c++ code



#include<iostream>
using namespace std;

int recursive_function(int n){
    static int i=1;// to make one time initialization
    cout<<i<<" : time"<<endl; // counting the function calls

    if(n==1){
      return 1;//base case
       }
   else{
        i++;
        return  n=n*recursive_function(n-1);
        }
}

int main(){

    cout<<"Enter to number to find Factorial: ";
    int num;
    cin>>num;
    num=recursive_function(num)// function call
    cout<<"\n\n\n\t\t\tFactorial of number is: "<<num;
    cout<<"\n\n\n\n\n";
return 0;
}



As a beginner some questions can be raised regarding code.
Why static variable is used instead of a simple int variable?

  • The property of static variable is that it is initialized when program runs first time
  • Its value increments on every call and it is not initializing again and again
  • if we do not use static keyword then variable ' int i=1;' will be initialize again and again and its value will not be correct at the end infact it will remain 1 always. 
  • So that is why static in has been used to count the number of calls

To provide more readable view here is image view of code:
c++ program to find factorial using recursinve function of given number

Sample Input Output
sample output factorial recusion cpp
Recommended:
To learn fast change the code and examine output.

1 comment:

  1. What are the advantages and disadvantages of using a binary tree which has been defined in a recursive way?

    ReplyDelete