Algorithm
1. Start
2. Read the base (a) and exponent (b) from the user
3. Set result = 1
4. Repeat b times:
4.1. Multiply result by the base
5. Display the result as the power of the number
6. End
Code Examples
#1 Code Example- Calculate power of a number using a while loop
Code -
Java Programming
class Main {
public static void main(String[] args) {
int base = 3, exponent = 4;
long result = 1;
while (exponent != 0) {
result *= base;
--exponent;
}
System.out.println("Answer = " + result);
}
}
Copy The Code &
Try With Live Editor
Output
#2 Code Example- Calculate the power of a number using a for loop
Code -
Java Programming
class Main {
public static void main(String[] args) {
int base = 3, exponent = 4;
long result = 1;
for (; exponent != 0; --exponent) {
result *= base;
}
System.out.println("Answer = " + result);
}
}
Copy The Code &
Try With Live Editor
Output
#3 Code Example- Calculate the power of a number using pow() function
Code -
Java Programming
class Main {
public static void main(String[] args) {
int base = 3, exponent = -4;
double result = Math.pow(base, exponent);
System.out.println("Answer = " + result);
}
}
Copy The Code &
Try With Live Editor
Output
#4 Code Example- Compute Power of Negative Number
Code -
Java Programming
class Main {
public static void main(String[] args) {
// negative number
int base = -3, exponent = 2;
double result = Math.pow(base, exponent);
System.out.println("Answer = " + result);
}
}
Copy The Code &
Try With Live Editor
Output
Demonstration
Java Programing Example to Calculate the Power of a Number-DevsEnv