Python/C/C++/JAVA

Moderate Practice Programs with Code and Concept

By D.S

Calculate Power using Recursion

If you want to write a program that calculates power using recursion, you'll need to understand how recursion works. Recursion is a programming technique where a function calls itself in order to solve a problem. In the case of calculating power, you can define a recursive function that multiplies the base number by itself recursively until the exponent becomes 0, at which point the result is returned. This approach can be implemented in various programming languages like C, C++, Python, or Java. By understanding the concept of recursion and implementing it in your code, you can efficiently calculate power using recursion.

(a.) C Code

#include <stdio.h>

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

int main(void) {
  int base = 2;
  int exponent = 3;
  printf("Result: %d", power(base, exponent));
  return 0;
}
Output:-
Enter base: 2
Enter exponent: 3
Result: 8

(b.) C++ Code

#include <iostream>
using namespace std;

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

int main() {
  int base = 2;
  int exponent = 3;
  cout << "Result: " << power(base, exponent);
  return 0;
}
Output:-
Enter base: 2
Enter exponent: 3
Result: 8

(c.) Python Code

def power(base, exponent):
  if exponent == 0:
      return 1
  else:
      return base * power(base, exponent - 1)

base = 2
exponent = 3
print("Result:", power(base, exponent))
Output:-
Enter base: 2
Enter exponent: 3
Result: 8

(d.) Java Code

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

  public static void main(String[] args) {
      int base = 2;
      int exponent = 3;
      System.out.println("Result: " + power(base, exponent));
  }
}
Output:-
Enter base: 2
Enter exponent: 3
Result: 8