 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- 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)); }Advertisements
 