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

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024