Java Program to calculate the power of a number


March 2, 2022, Learn eTutorial
1214

Here we are explaining how to write a java program to calculate the power of numbers. So first we have to read the number and its exponent from the user. Then we will calculate the power of the number using a while loop.

How to read a number in java?

To read an integer number from the user we can the nextInt() function in the java Scanner class.

Example: number = sc.nextInt() 

where sc is the object of the Scanner class.

How to calculate the power of a number in java?

First, declare the class PowerNum with a public modifier. Then open the main() function to declare the variable number, power, result. The set result equals 1.Read a number from the user and save it into the variable number. Read the exponent number from the user and save it into the variable p.Then initialize the variable i to the value of p.Then by using a while loop, check the condition i not equal to zero calculate the result as result=result*number. Decrement i by one and repeat the loop. Then display the result.

ALGORITHM

STEP 1: Declare the class PowerNum with public modifier 

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the variable number,p as integer, and result as long.

STEP 4: Assign result=1.

STEP 5: Read the number from the user into the variable number using nextInt() method in scanner class.

STEP 6: Read the exponent from the user into the variable p using nextInt() method in scanner class.

STEP 7: Assign i =p.

STEP 8: By using a while loop with the condition i!=0 then do step 9.

STEP 9: calculate result=result*number.

STEP 10: increment i by one and repeat step 8.

STEP 11:Display the result as number^p= result.

 

Java Source Code

                                          import java.util.Scanner;
public class PowerNum {
    public static void main(String[] args) {
        int number,p;
        long result = 1;
        Scanner sc = new Scanner(System.in);//Create the object of Scanner class.
        System.out.print("Enter the number:");
        number = sc.nextInt();//Read the number from the console
        System.out.print("Enter the Exponent:");
        p= sc.nextInt();//Read the Exponent from the console
        int i=p;
        while (i != 0)
        {
            result *= number;
            i--;
        }
        System.out.println(number+"^"+p+" = "+result);
    }
}
                                      

OUTPUT

OUTPUT 1

Enter the number:
2
Enter the Exponent:
2

2^2=4

OUTPUT 2

Enter the number:
5
Enter the Exponent:
3

5^3=125