Power of a number using Java

Power of a number using java :

In this article we will create a java program to calculate power of a number. The power of a number is the number multiplied to itself for the number of times it has been raised to. To calculate the power of a number we can directly use power() function, but we have created the program without using power function to make the program more  simple and easier.

For better understanding let us consider an example :

Suppose, 5 is the number and it is raised with the power 2 then its resultant will be 25.

5 ^ 2 = 25 ;

where 5 is said to be the base and 2 is said to be the exponent.

Power of a number using Java

Working :

Step 1 : Ask the user to enter the base value and the exponent value. 

Step 2 : Declare a variable for storing the result.

Step 3 : Use a loop to multiply base by itself till the exponent value does not becomes 0 and decrease the value of exponent after every iteration of the loop.

Step 4 :  Print the result.


Code in Java :

//Java program to calculate power of a number
import java.util.Scanner;
public class Power_of_a_number
public static void main(String[] args)
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input base value and exponent value from user
System.out.print("Enter the value of base : ");
int base = sc.nextInt();
System.out.print("Enter the value of exponent : ");
int exp = sc.nextInt();
//declare an integer variable to store the result
int result = 1;
//logic for calculating power of the entered number
while (exp != 0)
result = result * base;
//print the result
System.out.println("Answer = " + result);
//closing scanner class(not compulsory, but good practice)

Output :

Enter the value of base : 3
Enter the value of exponent : 4
Answer = 81