In this Java program, you’ll learn how to Calculate the Power of a Number using the Java programming language.
How to Calculate the Power of a Number?
Example 1: using for loop
RUN CODE SNIPPETclass Main {
public static void main(String[] args)
{
int base = 5, exponent = 2;
long result = 1;
for (; exponent != 0; --exponent)
{
result *= base;
}
System.out.println("Answer = " + result);
}
}OUTPUT
Answer = 25
Example 2:
RUN CODE SNIPPETclass Main {
public static void main(String[] args)
{
int base = 2, exponent = -4;
double result = Math.pow(base, exponent);
System.out.println("Answer = " + result);
}
}OUTPUT
Answer = 0.0625
Example 3: using recursion
RUN CODE SNIPPETimport java.util.Scanner;
public class Main
{
static int power(int b, int e)
{
if (e == 0)
return 1;
else
return b * power(b, e - 1);
}
public static void main(String args[])
{
int b, e;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the base: ");
b=sc.nextInt();
System.out.print("Enter the exponent: ");
e=sc.nextInt();
System.out.println(b +" to the power " +e + " is: "+power(b, e));
}
}OUTPUT
Enter the base: 3 Enter the exponent: 5 3 to the power 5 is: 243