In this tutorial, we are going to learn java program to calculate the power of a given number. To calculate the power, user will give the base number and the exponent number. We will calculate Power by multiplying the base number exponent times.
For example
Case1: If the user inputs the base of the number as 2 and exponent as 3
then the output should be ‘8’.
Case2: If the user inputs the base of the number as 5 and exponent as 2.
then the output should be ‘25’.
Power can be calculated using in built pow() method and using manual multiplications. In this tutorial we will see without pow().
Java Program to calculate Power without using POW() function
import java.util.*;
public class Main {
public static void main(String[] args) {
int base,exponent,result=1;
Scanner sc = new Scanner(System.in);
System.out.println("Please give the base number");
base= sc.nextInt();
System.out.println("Please give the exponent number");
exponent= sc.nextInt();
System.out.println(base+" to the power "+exponent);
while (exponent != 0) {
result = base * result;
--exponent;
}
System.out.println(result);
}
}
Output
Please give the base number
4
Please give the exponent number
3
4 to the power 3
64
Explanation
For the input from the user, the base number is 4, and the exponent number is 3. The ‘base e exponent’ will be 4^3, which is 4*4*4 i.e. 64.