Java program to calculate the power of a number

Java Programming Java8Object Oriented Programming

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
raja
Published on 26-Apr-2018 08:41:33
Advertisements