In this Java program, you’ll learn how to Calculate the Power of a Number using the Java programming language.
How to Calculate the Power of a Number?
Example 1: using for loop
RUN CODE SNIPPETclass Main { public static void main(String[] args) { int base = 5, exponent = 2; long result = 1; for (; exponent != 0; --exponent) { result *= base; } System.out.println("Answer = " + result); } }
Java
x
12
1
class Main {
2
public static void main(String[] args)
3
{
4
int base = 5, exponent = 2;
5
long result = 1;
6
for (; exponent != 0; --exponent)
7
{
8
result *= base;
9
}
10
System.out.println("Answer = " + result);
11
}
12
}
OUTPUT
Answer = 25
Example 2:
RUN CODE SNIPPETclass Main { public static void main(String[] args) { int base = 2, exponent = -4; double result = Math.pow(base, exponent); System.out.println("Answer = " + result); } }
Java
xxxxxxxxxx
1
1
class Main {
2
public static void main(String[] args)
3
{
4
int base = 2, exponent = -4;
5
double result = Math.pow(base, exponent);
6
System.out.println("Answer = " + result);
7
}
8
}
OUTPUT
Answer = 0.0625
Example 3: using recursion
RUN CODE SNIPPETimport java.util.Scanner; public class Main { static int power(int b, int e) { if (e == 0) return 1; else return b * power(b, e - 1); } public static void main(String args[]) { int b, e; Scanner sc=new Scanner(System.in); System.out.print("Enter the base: "); b=sc.nextInt(); System.out.print("Enter the exponent: "); e=sc.nextInt(); System.out.println(b +" to the power " +e + " is: "+power(b, e)); } }
C#
xxxxxxxxxx
1
21
1
import java.util.Scanner;
2
public class Main
3
{
4
static int power(int b, int e)
5
{
6
if (e == 0)
7
return 1;
8
else
9
return b * power(b, e - 1);
10
}
11
public static void main(String args[])
12
{
13
int b, e;
14
Scanner sc=new Scanner(System.in);
15
System.out.print("Enter the base: ");
16
b=sc.nextInt();
17
System.out.print("Enter the exponent: ");
18
e=sc.nextInt();
19
System.out.println(b +" to the power " +e + " is: "+power(b, e));
20
}
21
}
OUTPUT
Enter the base: 3 Enter the exponent: 5 3 to the power 5 is: 243