Website For Developers

Recursive function in C++




Program to find factorial in C++

//Program to find factorial
#include<iostream>
#include<conio.h>
using namespace std;
int findFactorial(int);
int main() {
  int number;
  cout<<"Enter an integer number to find factorial: "<<endl;
  cin >> number;
  int f = findFactorial(number);
  cout<<"Factorial of "<<Number<<" is "<<f;
  getch();
  return 0;
}
int findFactorial(int num){
  if (num > 0) {
    return num*findFactorial(num-1);
  }
  else {
    return 1;
  }
}

Output

Enter an integer number to find factorial: 4
Factorial of 4 is 24



Example of Fibonacci Series in C++

//Program to find Fibonacci Series
#include<iostream>
#include<conio.h>
using namespace std;
// Global variable declaration and initialization
int x=0,y=1,z=0;
void printFibo(int n){
  if(n>0){
  z = x + y;
  x = y;
  y = z;
  cout<<","<<z;
  printFibo(n-1);
  }
}
int main() {
  int number;
  cout<<"Enter Range of Fibonacci Series:";
  cin>>number;
  cout<<x","<<y;
  printFibo(number-2);
  getch();
  return 0;
}

Output

Enter Range of Fibonacci Series: 10
0,1,1,2,3,5,8,13,21,34