Write a C++ Program to Calculate Power Using Recursion

In programming, recursion is a technique where a function calls itself to solve a problem.

This technique can be used to solve a wide range of problems, including the calculation of powers.

In this tutorial, we will discuss how to calculate powers using recursion in C++.

Calculating Powers Using Recursion

In C++, we can calculate the power of a number by using a simple formula: base^exponent. To calculate the power of a number using recursion, we can use the following steps:

  • Define a function that takes two parameters: base and exponent.
  • If the exponent is 0, return 1. This is because any number raised to the power of 0 is always 1.
  • If the exponent is 1, return the base. This is because any number raised to the power of 1 is always equal to itself.
  • If the exponent is greater than 1, recursively call the function with the base and the exponent – 1, and multiply the result by the base.

Here is the C++ code for calculating powers using recursion:

#include <iostream>
using namespace std;

int power(int base, int exponent) {
  if (exponent == 0) {
    return 1;
  } else if (exponent == 1) {
    return base;
  } else {
    return base * power(base, exponent - 1);
  }
}

int main() {
  int base, exponent;
  cout << "Enter the base: ";
  cin >> base;
  cout << "Enter the exponent: ";
  cin >> exponent;
  cout << base << "^" << exponent << " = " << power(base, exponent);
  return 0;
}

In this code, we first define the power() function that takes two parameters: base and exponent.

We then use if-else statements to check whether the exponent is 0, 1, or greater than 1. If the exponent is 0, we return 1.

If the exponent is 1, we return the base. Otherwise, we recursively call the power() function with the base and the exponent – 1, and multiply the result by the base.

In the main() function, we ask the user to enter the base and exponent, and then call the power() function to calculate the power of the base to the exponent.