Calculate Power in Java: Explanation & Practice

Calculate base raised to exponent without Math.pow

Problem summary

Write a program that calculates base^exponent using a loop. Do NOT use Math.pow().

Starter code

public class Main {
    public static void main(String[] args) {
        int base = 2;
        int exponent = 10; // Test case 1
        
        // Calculate base^exponent using a loop (no Math.pow)
        // Print: Result: <result>
    }
}

Expected output and test cases

  • 2^10 = 1024
    Result: 1024
  • 3^4 = 81
    Result: 81
  • 5^0 = 1
    Result: 1

Hints

  1. Start with result = 1
  2. Multiply by base, exponent number of times
  3. Handle exponent = 0 (result is always 1)

Related Core Java Basics exercises

Practice all Core Java Basics exercises · Run this idea in the Java compiler