73
Power of a Number in Java
In this section, we will create Java programs to find the power of a number in Java. In order to find the power of a number, multiply the number itself up to exponent times.
Example:
Suppose, 5 is the base and 4 is the exponent. In order to find the power of a number, multiply the number itself 4 times, i.e. (5 * 5 * 5 * 5 = 625).
Steps to Find Power of a Number
- Read or initialize base and exponent.
- Take another variable (power) to store the result and initialize it to 1.
- Using the for loop or while loop, multiply the base by power and store the result into power.
- Repeat the above step (3) until the exponent becomes 0.
- Print the result.
Let’s implement the above steps in a Java program.
Java Program to Find the Power of a Number
There are the following ways to find the power of a number:
- Using Java for Loop
- Using Java while Loop
- Using Recursion
- Using Java Math.pow() Method
Using for Loop
PowerOfNumberExample1.java
Output:
Enter the base: 11 Enter the exponent: 3 11 to the power 3 is: 1331
In the above program, we can replace the for loop with the following for loop, the logic is quite different but gives the same result.
Using while Loop
PowerOfNumberExample2.java
Output:
Enter the base: 7 Enter the exponent: 6 7 to the power 6 is: 117649
Using Recursion
PowerOfNumberExample3.java
Output:
Enter the base: 12 Enter the exponent: 4 12 to the power 4 is: 20736
Using Math.pow() Method
PowerOfNumberExample2.java
Output 1:
Enter the base: 2 Enter the exponent: 5 2 to the power 5 is: 32.0
Output 2:
Enter the base: 8 Enter the exponent: -3 8 to the power -3 is: 0.001953125
Output 3:
Enter the base: -10 Enter the exponent: 3 -10 to the power 3 is: -1000.0
Next TopicSum of Prime Numbers in Java