C - Write program to calculate power with recursive function

Requirements

A function with the prototype

double power(double x, int n);

should calculate and return the value of x^n .

The expression power(5.0, 4) will evaluate 5.0 * 5.0 * 5.0 * 5.0, which will result in the value 625.0.

Implement the power() function as a recursive function

Use the operation with a suitable version of main().

Demo

#include <stdio.h>

double power(double x, int n);


int main(void)
{
  for (double x = 2.0; x <= 5.0; x += 0.5)
  {//from  w w  w . ja v a  2  s. c  om
    for (int n = -4; n < 5; ++n)
      printf("The value of %.2lf raised to the power %d is %.4lf\n", x, n, power(x, n));
    printf("\n");
  }

  return 0;
}

// Function to raise x to the power n
double power(double x, int n) {
  if (n < 0)
  {
    n = -n;
    x = 1.0 / x;
  }

  if (n == 0)
    return 1.0;

  return x * power(x, n - 1);
}

Result

Related Exercise