Java Program to Calculate the Power of a Number - The Coding Shala

Home >> Java Programs >> Power of a Number

 In this post, we will learn how to Calculate the Power of a Number using the loop and Math.pow() method in Java.

Java Program to Calculate the Power of a Number

You have given a number N ( base) and power p (exponent). Write a Java Program to Calculate the power of the number N.

Example 1:
Input: N = 3
          P = 4
Output: 81

Approach 1

Using loop.

Java Program: 

// Java program to calculate power of a number

public class Main {
	
	public static void main(String[] args) { 
		// inputs can be taken using scanner
		int base = 3;
		int exponent = 4;
		
		int power = 1;
		// using loop
		for(int i = 1; i <= exponent; i++) {
			power = power * base;
		}
		
		System.out.println("power(" + base + "," + exponent + ") is: " + power);
	}
}

Approach 2

We can also use Java's inbuilt Math.pow() method to calculate the power.

Java Program: 

// Java program to calculate power of a number

public class Main {
	
	public static void main(String[] args) { 
		// inputs can be taken using scanner
		int base = 3;
		int exponent = 4;
		
		// using Math.pow()
		// pow method will return double
		double power = Math.pow(base, exponent);
		
		System.out.println("power(" + base + "," + exponent + ") is: " + power);
	}
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

New Year Chaos Solution - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala