Home » Power of a Number in Java

Power of a Number in Java

by Online Tutorials Library

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.

Power of a Number in Java

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).

Power of a Number in Java

Steps to Find Power of a Number

  1. Read or initialize base and exponent.
  2. Take another variable (power) to store the result and initialize it to 1.
  3. Using the for loop or while loop, multiply the base by power and store the result into power.
  4. Repeat the above step (3) until the exponent becomes 0.
  5. 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 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  

You may also like