Showing posts with label recursion. Show all posts
Showing posts with label recursion. Show all posts

Tuesday, June 16, 2020

Write a program to compute a^n (a power n) using recursion.

INPUT & OUTPUT FORMAT:

Input consists of 2 integers

Refer sample input and output for formatting specifications

SAMPLE INPUT & OUTPUT:

Enter the value of a

2

Enter the value of n

8

The value of 2 power 8 is 256

SOLUTION:

#include<iostream>

using namespace std;

int pow(int n, int p){

  while(p>1){

    return n * pow(n,p-1);

  }

}

int main()

{

  cout<<"Enter the value of a"<<endl<<"Enter the value of n"<<endl;

  int n,p;

  cin>>n>>p;

  cout<<"The value of "<<n<<" power "<<p<<" is "<<pow(n,p);

  return 0;

}


Write a program to find the nth term in the Fibonacci series using recursion

INPUT & OUTPUT FORMAT:

Input consists of an integer.

Refer sample input and output for formatting specifications.

All text in bold corresponds to the input and the rest corresponds to output.

SAMPLE INPUT & OUTPUT:

5

The term 5 in the fibonacci series is 3

SAMPLE INPUT & OUTPUT:

15

The term 5 in the fibonacci series is 377

SAMPLE INPUT & OUTPUT:

8

The term 5 in the fibonacci series is 13

SOLUTION

#include<iostream>
using namespace std;
int fibonacci(int n){
  int a[n];
  a[0] = 0;
  a[1] = 1;
  for(int i = 2; i < n; i++){
    a[i] = a[i-1] + a[i-2];
  }
  return a[n-1];
}
int main()
{
  int n;
  cin>>n;
  cout<<"The term "<<n<<" in the fibonacci series is "<<fibonacci(n);
  return 0;

}

Factorial of a number using recursion in C++

#include<iostream> 

using namespace std;

int factorial (int a){

if(a > 1){
return a * factorial(a-1);
}
else
return 1;
}

int main(){
  int n;
  cin>>n;
  cout<<"The factorial of "<<n<<" is "<<factorial(n);
}

GCD Using Recursion in C++


    #include<iostream>
    using namespace std;
    void rec(int a,int b, int l){
      if(a % l == 0 && b % l == 0){  
        cout<<"G.C.D of "<<a<<" and "<<b<<" = "<<l;
      return;
      }
      rec(a,b,--l);  
    }

    int main(){
      int x,y,s;
      cin>>x>>y;
      if(x<y)
        s = x;
      else
        s = y;
      rec(x,y,s);
    }

horizontal ads