Power of a Number in JavaIn 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
Let's implement the above steps in a Java program. Java Program to Find the Power of a NumberThere are the following ways to find the power of a number:
Using for LoopPowerOfNumberExample1.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 LoopPowerOfNumberExample2.java Output: Enter the base: 7 Enter the exponent: 6 7 to the power 6 is: 117649 Using RecursionPowerOfNumberExample3.java Output: Enter the base: 12 Enter the exponent: 4 12 to the power 4 is: 20736 Using Math.pow() MethodPowerOfNumberExample2.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
|