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().
Program : Calculate Power without using POW() in Java
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
5
Please give the exponent number
3
5 to the power 3
125
Explanation
For the input from the user, the base number is 5, and the exponent number is 3. The ‘base e exponent’ will be 5^3, which is 5*5*5 i.e. 125.