Write a Java Program to Calculate the Power of a Number

Java Program to Calculate the Power of a Number

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Calculate the Power of a Number
Java Program to Calculate the Power of a Number

Write a Java Program to Calculate the Power of a Number

PROGRAM: Java Program to Calculate the Power of a Number

/* Java Program to Calculate the Power of a Number */

1: Calculate power of a number using a while loop

class Main {
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);
}
}

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

class Main {
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);
}
}

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

class Main {
public static void main(String[] args) {

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

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

4: Compute Power of Negative Number

class Main {
public static void main(String[] args) {

// negative number
int base = -3, exponent = 2;

double result = Math.pow(base, exponent);
System.out.println(“Answer = ” + result);
}
}

 

 

Leave a Reply

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