HomeJavaJava Program to Calculate the Power of a Number

Java Program to Calculate the Power of a Number

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

OUTPUT 

Answer = 25

Example 2: 

RUN CODE SNIPPET
class Main { 
  public static void main(String[] args)  
  { 
    int base = 2, exponent = -4; 
    double result = Math.pow(base, exponent); 
    System.out.println("Answer = " + result); 
  } 
}

OUTPUT 

Answer = 0.0625

Example 3: using recursion 

RUN CODE SNIPPET
import 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));   
}   
}

OUTPUT 

Enter the base: 3 
Enter the exponent: 5 
3 to the power 5 is: 243

Share:

Leave A Reply

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

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022