Power without Math.pow() in Java

Compute a^b using a loop instead of Math.pow().

BeginnerModule 1: Basic Java ProgramsExample 16 of 20
power-without-math-pow.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6
7 System.out.print("Enter base (a): ");
8 int a = sc.nextInt();
9 System.out.print("Enter exponent (b): ");
10 int b = sc.nextInt();
11
12 long result = 1;
13 for (int i = 1; i <= b; i++) {
14 result *= a;
15 }
16
17 System.out.println(a + " raised to " + b + " = " + result);
18
19 sc.close();
20 }
21}

Output

Enter base (a): 2
Enter exponent (b): 5
2 raised to 5 = 32

What's going on

We multiply the base by itself b times in a loop to compute a^b.