Java Program to Calculate the Power of a Number

Java Program to Calculate the Power of a Number

In this example, we will learn to calculate the power of a number with and without using pow() function.

Example 1: 

public class Power {

    public static void main(String[] args) {

        int base = 4, exponent = 7;

        long result = 1;

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

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

 

Output :

Answer = 16384

In this program, base and exponent are assigned values 4 and 7 respectively.

Using the while loop, we keep on multiplying result by base until exponent becomes zero.

Example 2: 

public class Power {

    public static void main(String[] args) {

        int base = 4, exponent = 7;

        long result = 1;

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

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

Output :

Answer = 16384

Example 3:

public class Power {

    public static void main(String[] args) {

        int base = 8, exponent = 2;
        double result = Math.pow(base, exponent);

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

Output :

Answer = 64.0