Using Java

  • calculate power of a number using for loop

Here number is the base and p is the power (exponent). So we are calculating the result of 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);
    }
}
  • calculate 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);
    }
}