How to Find Power of a Number in Java Program ?

  Java Interview Q&A

Dear reader, today we will read in Java program to to find power of a number.

Java Program to calculate power of a number using while loop

public class JavaExample {
    public static void main(String[] args) {
        int number = 5, p = 2;
        long result = 1;
        
        int i=p;
        while (i != 0)
        {
            result *= number;
            --i;
        }
        System.out.println(number+"^"+p+" = "+result);
    }
}

Output :

5^2 = 25

To calculate the Power of a number using a Java program loop

In this program we are calculating the power of a given number for a loop. Here the number is the base and p is the power (exponent). Therefore we are calculating the result of the number ^ p.

public class JavaExample {
    public static void main(String[] args) {
    	//Here number is the base and p is the exponent
        int number = 2, p = 5;
        long result = 1;
        
        //Copying the exponent value to the loop counter
        int i = p;
        for (;i != 0; --i)
        {
            result *= number;
        }
        
        //Displaying the output
        System.out.println(number+"^"+p+" = "+result);
    }
}

Output :

2^5 = 32

Java Program to find power of a number using pow() function

public class JavaExample {
    public static void main(String[] args) {
    	int number = 10, p = 3;
        double result = Math.pow(number, p);
        System.out.println(number+"^"+p+" = "+result);
    }
}

Output :

10^3 = 1000.0

Read here complete . JAVA Program Tutorial

LEAVE A COMMENT