Find Power of a Number in Java using For loop
ADVERTISEMENTS
Find power of a number in java using for loop. In this article, you will learn how to find power of a number in java using for loop.
Syntax to calculate the power of N number
x ^ y = results
Find Power of a Number in Java using For loop
// Find Power of a Number in Java using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int b, x, i;
double r = 1;
// b - To store base number
// x - To store exponent number
// r - To store result value
System.out.println ("-----Enter the input of base number-----");
b = in.nextInt();
System.out.println ("\n-----Enter the input of exponent number-----");
x = in.nextInt();
for (i = x; i > 0; i--) {
r *= b;
}
System.out.println ("\nThe calculation of the power of N number is " + b + "^" + x + " = " + r);
}
}
Output
-----Enter the input of base number-----
8
-----Enter the input of exponent number-----
4
The calculation of the power of N number is 8^4 = 4096.0
Find Power of a Number in Java using Math.pow() Function
// Find Power of a Number in Java using Math.pow() Function
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double b, x, r;
// b - To store base number
// x - To store exponent number
// r - To store result value
System.out.println ("-----Enter the input of base number-----");
b = in.nextFloat();
System.out.println ("\n-----Enter the input of exponent number-----");
x = in.nextFloat();
r = (double) Math.pow(b, x);
System.out.println ("\nThe calculation of the power of N number is " + b + "^" + x + " = " + r);
}
}
Output
-----Enter the input of base number-----
10
-----Enter the input of exponent number-----
3.5
The calculation of the power of N number is 10.0^3.5 = 3162.2776601683795