Java Program to Calculate the Power of a Number

In this program, you'll learn to calculate the power of a number in Java.

Calculate the Power of a Number using a For Loop

public class Power {
public static void main(String[] args) {
int base = 3, exponent = 3;
long result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
System.out.println(base + " to the power of " + exponent + " is equal to " + result);
}
}
view raw Power.java hosted with ❤ by GitHub

When you run the program, the output will be:

3 to the power of 3 is equal to 27



Calculate the Power of a Number using a While Loop

public class Power {
public static void main(String[] args) {
int base = 3, exponent = 3;
int i = 0;
long result = 1;
while (i < exponent) {
result *= base;
i++;
}
System.out.println(base + " to the power of " + exponent + " is equal to " + result);
}
}
view raw Power.java hosted with ❤ by GitHub

When you run the program, the output will be:

2 to the power of 5 is equal to 32

Post a Comment

Thank you for vising

أحدث أقدم