Java Program to find Power of a Number

Write a Java Program to find Power of a Number using For Loop, and While Loop. You can also use Java math.pow function to calculate Power of a Number.

Java Program to find Power of a Number Using For Loop

This program allows the user to enter a Number and exponent value. By using these values, this Java program calculates the Power of a given number using For Loop.

// Java Program to find Power of a Number
import java.util.Scanner;

public class PowerofaNumber {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int number, i, exponent;
		long power = 1;
		sc = new Scanner(System.in);
		
		System.out.print(" Please Enter any Number : ");
		number = sc.nextInt();	
		
		System.out.print(" Please Enter the Exponent Value : ");
		exponent = sc.nextInt();	
		
		for(i = 1; i <= exponent; i++)
		{
			power = power * number;
		}
		System.out.println("\n The Final result of " + number + " power " + exponent + " = " + power);
	}
}
Java Program to find Power of a Number 1

We initialized the integer i value to 1, and also (i <= exponent) condition helps the loop to terminate when the condition fails.

for(i = 1; i <= exponent; i++)
{
	power = power * number;
}

User entered values in the above Java example are: number = 5, and exponent = 3
First Iteration: for(i = 1; i <= 3; i++)
It means condition inside the For loop (1 <= 3) is True
power = 1 * 5 = 5
i++ means i becomes 2

Second Iteration: for(i = 2; i <= 3; i++)
It means condition inside the For loop (2 <= 3) is True
power = 5 * 5 = 25
i becomes 3

Third Iteration: for(i = 3; 3 <= 3; i++)
power = 5 * 25 = 125
i becomes 4

Fourth Iteration: for(i = 4; i <= 3; i++). It means condition inside the For loop (4 <= 3) is False. So, the compiler comes out of the For Loop and prints the output.

Java Program to find Power of a Number Using While Loop

This Java program calculates the power of any given number using While Loop.

We just replaced the For loop in the above Java program example with the While loop. If you don’t understand the While Loop, please refer While Loop article here: WHILE LOOP.

// Java Program to find Power of a Number
import java.util.Scanner;

public class PowerofaNumber1 {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int number, i = 1, exponent;
		long power = 1;
		sc = new Scanner(System.in);
		
		System.out.print(" Please Enter any Number : ");
		number = sc.nextInt();	
		
		System.out.print(" Please Enter the Exponent Value : ");
		exponent = sc.nextInt();	
		
		while(i <= exponent)
		{
			power = power * number;
                        i++;
		}
		System.out.println("\n The Final result of " + number + " power " + exponent + " = " + power);
	}
}
 Please Enter any Number : 4
 Please Enter the Exponent Value : 5

 The Final result of 4 power 5 = 1024