Write a Java program to calculate the power of a number using recursion


This program prompts the user to input a base number and a power number, and calculates the result of raising the base to the power using a recursive function. Here's how the program works:

  • The program prompts the user to input a base number and a power number.
  • It then calls the calulatePower function with the base number and power number as arguments.
  • The calulatePower function recursively calculates the result by multiplying the base number by the result of calling calulatePower with the same base number and a decremented power number.
  • The recursion continues until the power number reaches 0, at which point the function returns 1.
  • The calculated result is returned to the main function and printed to the console.

Overall, the program works correctly and efficiently to calculate the result of raising a number to a power using recursion.

Source Code

import java.util.*;
public class PowerNumber
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.printf("Enter the Base Number : ");
		int base = input.nextInt();
		System.out.printf("Enter the Power Number : ");
		int pow = input.nextInt();
		int res = calulatePower(base, pow);
		System.out.printf("Result : " + res);
	}
	public static int calulatePower(int b, int p)
	{
		int res = 1;
		if (p > 0)
		{
			res = b * (calulatePower(b, p - 1));
		}
		return res;
	}
}

Output

Enter the Base Number : 4
Enter the Power Number : 3
Result : 64