Java program to calculate the power of a number


Read the base and exponent values from the user. Multiply the base number by itself and multiply the resultant with base (again) repeat this n times where n is the exponent value.

2 ^ 5 = 2 X 2 X 2 X 2 X 2 (5 times)

Example

import java.util.Scanner;
public class PowerOfNumber {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the base number ::");
      int base = sc.nextInt();
      int temp = base;
      System.out.println("Enter the exponent number ::");
      int exp = sc.nextInt();

      for (int i=1; i<exp; i++){
         temp = temp*temp;
      }
      System.out.println("Result of "+base+" power "+exp+" is "+temp);
   }
}

Output

Enter the base number ::
12
Enter the exponent number ::
2
Result of 12 power 2 is 144

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 13-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements