Deitel C++ How To Program 9th Edition Chapter 6 Exercise 6.36

15 Jul 2024 - Syed Muhammad Shahrukh Hussain

Write a program which implements the power function using recursion.

Terminal

Enter number: 2
Enter exponent: 2
Exponential: 4

Solution

#include <iostream>

using namespace std;

int exponential(int number, int n);

int main() {
  int number;
  int exponent;

  cout << "Enter number: ";
  cin >> number;
  cout << "Enter exponent: ";
  cin >> exponent;
  cout <<  "Exponential: " << exponential(number, exponent) << endl;
  return 0;
}

int exponential(int number, int n) {
  // base case as number ^ 0 = 1
  if (0 == n) {
    return 1;
  }
  return number * exponential(number, n - 1);
}

Sources