In this article, we will understand how to calculate the power of a number. The power of a number is calculated using a loop and multiplying it by itself multiple times.
Below is a demonstration of the same −
Input
Suppose our input is −
Number : 4 Exponent value : 5
Output
The desired output would be the following i.e. 45
The result is 1024
Algorithm
Step 1 - START Step 2 – Declare two integer values namely my_input and my_exponent Step 3 - Read the required values from the user/ define the values Step 4 – Using a while loop, multiply the input value with itself for n number of times where n is the exponent value. Store the result. Step 5- Display the result Step 6- Stop
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool
.
import java.util.Scanner;
public class Exponents {
public static void main(String[] args) {
int my_input , my_exponent;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter the number : ");
my_input = my_scanner.nextInt();
System.out.print("Enter the exponent value : ");
my_exponent = my_scanner.nextInt();
long my_result;
my_result = 1;
while (my_exponent != 0) {
my_result *= my_input;
--my_exponent;
}
System.out.println("The result is = " + my_result);
}
}Output
Required packages have been imported A reader object has been defined Enter the number : 4 Enter the exponent value : 5 The result is = 1024
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
public class Exponents {
public static void main(String[] args) {
int my_input , my_exponent;
my_input = 4;
my_exponent = 5;
System.out.println("The number is defined as " +my_input +" and the exponent is defined as " + my_exponent);
long my_result;
my_result = 1;
while (my_exponent != 0) {
my_result *= my_input;
--my_exponent;
}
System.out.println("The result is = " + my_result);
}
}Output
The number is defined as 4 and the exponent is defined as 5 The result is = 1024