Calculate Power Using Recursion in C++



Calculating a power means multiplying the base by itself as many times as the exponent indicates. In this article, we'll show you how to write a C++ program to calculate the power of a number using recursion

For example, 2 raised to the power of 3 (2^3) means multiplying 2 by itself 3 times: 2 * 2 * 2, which gives 8.

Using Recursion to Calculate Power

To calculate the power of a number, we use recursion, where a function keeps calling itself with smaller values until it reaches a stopping point.

Here are the steps we took:

  • First, we check if the exponent is 0. If it is, we return 1 because any number raised to the power of 0 is 1.
  • Then, if the exponent is not 0, we multiply the base with the result of calling the same function again, but with the exponent reduced by 1.
  • Next, this process keeps repeating and each time it reduces the exponent by 1 until it becomes 0.
  • Once that happens, we stop and multiply all the results together to get the final answer.

C++ Program to Calculate Power Using Recursion

Here's a C++ program where we calculate the power of a number using recursion.

#include <iostream>
using namespace std;

int power(int base, int exponent) {
    if (exponent == 0) return 1;  // Base case
    return base * power(base, exponent - 1);  // Recursive call
}

int main() {
    int base = 2, exponent = 3; // Values directly assigned

    int result = power(base, exponent);
    cout << base << " raised to the power " << exponent << " is: " << result << endl;
    return 0;
}

Below is the output of the program, showing that 2 raised to the power of 3 is 8.

2 raised to the power 3 is: 8

Time Complexity: O(n) because it makes n recursive calls.

Space Complexity: O(n) because each call adds to the call stack.

Updated on: 2025-05-13T17:12:30+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements