Power of Number in Java
Compute a^b using a loop (similar to earlier power program).
BeginnerModule 3: Loop ProgramsExample 13 of 25
power-of-number.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter base: ");7 int a = sc.nextInt();8 System.out.print("Enter exponent: ");9 int b = sc.nextInt();1011 long result = 1;12 for (int i = 1; i <= b; i++) {13 result *= a;14 }1516 System.out.println(a + " ^ " + b + " = " + result);17 sc.close();18 }19}
Output
Enter base: 3 Enter exponent: 4 3 ^ 4 = 81
What's going on
Loop multiply, start from 1. Math.pow exists; this is so you see exponentiation is repeated multiply. ^ in Java is XOR. Use the wrong one and you get a mystery integer.