java

Java Program to find Power of a Number

In this tutorial, we are going to see how to find the power of a number in Java.

In the following example, we calculate the power of a given number using the for loop. Here, the number (x) is the base and n is the power (exponent). We, therefore, calculate the result of xn.
 

Java Program to find Power of a Number
public class Main {
    public static void main(String[] args) {
        //x is the base, n is the exponent
        int x = 4, n = 2;
        long res = 1;
        
        int i = n;
        for (;i != 0; --i)
        {
            res = res * number;
        }
        
        //display the result
        System.out.println(x+"^"+n+" = "+res);
    }
}

Output:

4^2 = 16
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *