- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Raise x to the power n using Recursion in Java

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

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)); }

- Related Articles
- Java Program to calculate the power using recursion
- Java program to calculate the power of a Given number using recursion
- Raise a square matrix to the power n in Linear Algebra in Python
- Haskell Program to calculate the power using Recursion
- Golang Program to Calculate The Power using Recursion
- How to display raise to the power on X-axis in base R plot?
- C++ Program to Calculate Power Using Recursion
- Java Program to Find Sum of N Numbers Using Recursion
- How to Find the Power of a Number Using Recursion in Python?
- Raise a polynomial to a power in Python
- How to calculate Power of a number using recursion in C#?
- Find power of a number using recursion in C#
- C program to generate the value of x power n using recursive function
- Raise a Hermite series to a power in Python
- Raise a Laguerre series to a power in Python

Advertisements