Write a program to find the value of one number raised to the power of another


The program first imports the java.util.Scanner package to allow user input. It then declares a class called Power and a main method, which is the entry point of the program.

Within the main method, the program prompts the user to enter a base number and a power number for which they want to calculate the result. The inputted values are stored in the variables base and power, respectively. It then initializes a variable result to 1.

Next, the program runs a for loop from 1 to power, multiplying the value of result by base each time through the loop. For example, if base is 2 and power is 5, the loop will run from 1 to 5, multiplying result by 2 each time through the loop, resulting in result equaling 32. Finally, the program prints out the calculated result.

Source Code

import java.util.Scanner;
class Power
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);        
		System.out.print("Enter the Base Number :");
		int base = input.nextInt();        
		System.out.print("Enter the Power Number :");
		int power = input.nextInt();
		int result = 1;
		for(int i = 1; i <= power; i++)
		{
			result *= base;
		}
 
		System.out.println("Result: "+ result);
	}
}

Output

Enter the Base Number :2
Enter the Power Number :5
Result: 32

Example Programs