Java Program to Calculate the Power of a Number

Example 1: Calculate power of a number using a while loop

public class Power {

    public static void main(String[] args) {

        int base = 3, exponent = 4;

        long result = 1;

        while (exponent != 0)
        {
            result *= base;
            --exponent;
        }

        System.out.println("Answer = " + result);
    }
}

Output

Answer = 81

Example 2: Calculate the power of a number using a for loop

public class Power {

    public static void main(String[] args) {

        int base = 3, exponent = 4;

        long result = 1;

        for (;exponent != 0; --exponent)
        {
            result *= base;
        }

        System.out.println("Answer = " + result);
    }
}

Output

Answer = 81

Example 3: Calculate the power of a number using pow() function

public class Power {

    public static void main(String[] args) {

        int base = 3, exponent = -4;
        double result = Math.pow(base, exponent);

        System.out.println("Answer = " + result);
    }
}

Output

Answer = 0.012345679012345678

Leave a Reply