Q:

Write C++ program to find power of a number using recursion

0

Write C++ program to find power of a number using recursion

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.

#include <iostream>
#include <math.h>
using namespace std;
 
//function declaration
double Power(double base, int exponent);
 
int main()
{
    double base, power;
    int exponent;
 
    // Inputting base and exponent from user
    cout<<"Enter base: ";
    cin>>base;
    cout<<"Enter exponent: ";
    cin>>exponent;
 
    // Call Power function
    power = Power(base, exponent);
 
    //printf("%.2lf ^ %d = %f", base, exponent, power);
    cout<<base<< "^"<<exponent<<" = "<<power;
 
    return 0;
}
 
/*
  Calculating power of any number.
  Returns base ^ exponent
 */
double Power(double base, int exponent)
{
    // Base condition
    if(exponent == 0)
        return 1;
    else if(exponent > 0)
        return base * pow(base, exponent - 1);
    else
        return 1 / pow(base, - exponent);
}

Result:

Enter base: 5

Enter exponent: 3

5^3 = 125

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write C++ program to find sum of natural numbers i... >>
<< Write C++ program to print perfect numbers between...