Java program to calculate the power using recursion

‮ptth‬s://www.theitroad.com

Here's a Java program to calculate the power of a number using recursion:

import java.util.Scanner;

public class PowerRecursion {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the base number: ");
        int base = scanner.nextInt();
        System.out.print("Enter the exponent: ");
        int exponent = scanner.nextInt();
        int result = power(base, exponent);
        System.out.println(base + "^" + exponent + " = " + result);
    }

    public static int power(int base, int exponent) {
        if (exponent == 0) {
            return 1;
        } else if (exponent % 2 == 0) {
            int temp = power(base, exponent / 2);
            return temp * temp;
        } else {
            return base * power(base, exponent - 1);
        }
    }
}

Explanation:

The program first creates a Scanner object to read user input from the console. It then prompts the user to enter the base number and exponent by printing the messages "Enter the base number: " and "Enter the exponent: " to the console.

The nextInt method of the Scanner object is called to read the next integer values entered by the user and store them in the base and exponent variables.

The program then calls the power method to calculate the power of the base number raised to the exponent. The result is stored in the result variable.

The power method is a recursive function that calculates the power of a number using the exponentiation by squaring algorithm. If the exponent is 0, the method returns 1. Otherwise, if the exponent is even, the method calculates the power of the base number raised to half the exponent, squares it, and returns the result. If the exponent is odd, the method calculates the power of the base number raised to the exponent - 1, multiplies it by the base number, and returns the result.

The program then prints the result to the console.

Note that this program assumes that the user will enter valid integer values. If the user enters non-integer values, the program will throw a java.util.InputMismatchException. To handle this case, you could wrap the nextInt calls in try-catch blocks to catch the exception and handle it appropriately.