English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)/O)

Java Reader/Writer

Other Java Topics

Java program to calculate power using recursion

Java Examples Comprehensive

In this program, you will learn how to use recursive functions in Java to calculate the power of a number.

Example: Program to calculate power using recursion

public class Power {
    public static void main(String[] args) {
        int base = 3, powerRaised = 4;
        int result = power(base, powerRaised);
        System.out.printf("%d^%d = %d", base, powerRaised, result);
    }
    public static int power(int base, int powerRaised) {
        if (powerRaised != 0)
            return (base * power(base, powerRaised - 1));
        else
            return 1;
    }
}

When the program is run, the output is:

3^4 = 81

In the above program, you use the recursive function power() to calculate the power.

Simply put, the recursive function multiplies the base with itself to obtain the number of times the power is raised, that is:

3 * 3 * 3 * 3 = 81
Execution Steps
Iterationpower()powerRaisedresult
1power(3, 4)43 * result2
2power(3, 3)33 * 3 * result3
3power(3, 2)23 * 3 * 3 * result4
4power(3, 1)13 * 3 * 3 * 3 * resultfinal
Finalpower(3, 0)03 * 3 * 3 * 3 * 1 = 81

Java Examples Comprehensive