Create a recursive function power to calculate Exponentiation - C++ Function

C++ examples for Function:Recursive Function

Description

Create a recursive function power to calculate Exponentiation

Demo Code

#include <iostream>

int power(int, int);

int main(int argc, const char *argv[]) {
    int base, exponent;

    std::cout << "A program to recursively calculate exponents" << std::endl;

    std::cout << "\nEnter the base and exponent: ";
    std::cin >> base >> exponent;

    std::cout << base << " to the power of " << exponent << ": "
              << power(base, exponent) << std::endl;
    return 0;//from   ww w . ja  v  a2  s  .  c o  m
}
// recusively calculate exponents
int power(int base, int exponent) {
    if (exponent == 0) return 1;

    return base * power(base, exponent - 1);
}

Result


Related Tutorials