Calculate power using recursion in Java
In this post, you will learn how to write a Java program to get the power of a number using a recursion function.
Recursion function is a function which is called by itself. In the given example, we call the recursion function to get the power of a number. A recursion function continues until some condition is met to prevent it. That's why we use the if else statement to break the infinite recursion.
The following Java program calculates the base power exponent using a recursive function. In this program, we read the value of base and exponent from the user input, and then we calculate baseexponent using a recursive function power(). If the exponential power isn't equal to 0, the base number multiplied with the power function is called recursively with the arguments as the base and exponent minus 1.
import java.util.Scanner;
public class power_num {
public static int power(int base, int exp){
if (exp !=0){
return (base * power(base, exp-1));
}else {
return 1;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the base number :");
int base = sc.nextInt();
System.out.println("Enter the exponent number :");
int exp = sc.nextInt();
System.out.println("Output : "+power(base, exp));
}
}
Output of the above code:
Enter the base number : 4
Enter the exponent number : 3
Output : 64
Enter the base number : 4
Enter the exponent number : 0
Output : 1
Enter the base number : 5
Enter the exponent number : 1
Output : 5
Enter the base number : 7
Enter the exponent number : 2
Output : 49
Related Articles
Sort array in ascending order JavaAutomorphic number in Java
Pascal triangle program in Java
Factorial using recursion in java
Java random number between 1 and 10
Palindrome program in Java
Floyd triangle in Java
Pyramid pattern programs in Java
Star pattern programs in Java
Number pattern programs in Java
Java program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java