# Raise x to the power n using Recursion in Java

Java 8Object Oriented ProgrammingProgramming

The power of a number can be calculated using recursion. Here the number is x and it is raised to power n.

A program that demonstrates this is given as follows:

## Example

Live Demo

public class Demo {
static double pow(double x, int n) {
if (n != 0)
return (x * pow(x, n - 1));
else
return 1;
}
public static void main(String[] args) {
System.out.println("7 to the power 3 is " + pow(7, 3));
System.out.println("4 to the power 1 is " + pow(4, 1));
System.out.println("9 to the power 0 is " + pow(9, 0));
}
}

## Output

7 to the power 3 is 343.0
4 to the power 1 is 4.0
9 to the power 0 is 1.0

Now let us understand the above program.

The method pow() calculates x raised to the power n. If n is not 0, it recursively calls itself and returns x * pow(x, n - 1). If n is 0, it returns 1. A code snippet which demonstrates this is as follows:

static double pow(double x, int n) {
if (n != 0)
return (x * pow(x, n - 1));
else
return 1;
}

In main(), the method pow() is called with different values. A code snippet which demonstrates this is as follows:

public static void main(String[] args) {
System.out.println("7 to the power 3 is " + pow(7, 3));
System.out.println("4 to the power 1 is " + pow(4, 1));
System.out.println("9 to the power 0 is " + pow(9, 0));
}
Published on 15-Feb-2019 12:18:43