In this article, we will write java programs to calculate power of a number.
1. Program to calculate power of a number using for loop
In this program we are calculating the power of a given number using for loop. Here number is the base and p is the power (exponent). So we are calculating the result of number^p.
public class JavaExample {
public static void main(String[] args) {
//Here number is the base and p is the exponent
int number = 2, p = 5;
long result = 1;
//Copying the exponent value to the loop counter
int i = p;
for (;i != 0; --i)
{
result *= number;
}
//Displaying the output
System.out.println(number+"^"+p+" = "+result);
}
}
Output:

2. Program to calculate power of a number using while loop
Here we are writing the same program that we have seen above using while loop.
public class JavaExample {
public static void main(String[] args) {
int number = 5, p = 2;
long result = 1;
int i=p;
while (i != 0)
{
result *= number;
--i;
}
System.out.println(number+"^"+p+" = "+result);
}
}
Output:

3. Program to calculate power of a number using pow() function
In the above two programs, we have seen how to calculate power of a number using loops. In the following program, we are using pow() function to calculate power.
public class JavaExample {
public static void main(String[] args) {
int number = 10, p = 3;
double result = Math.pow(number, p);
System.out.println(number+"^"+p+" = "+result);
}
}
Output:

Related Java Examples:
1. Java program to find quotient and remainder
2. Java program to calculate simple interest
3. Java program to calculate compound interest
4. Java program to print Pascal’s Triangle
Leave a Reply