Java program to calculate the power of a number

http‮ww//:s‬w.theitroad.com

Here's a Java program to calculate the power of a number:

import java.util.Scanner;

public class Power {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the base number: ");
        double base = scanner.nextDouble();
        System.out.print("Enter the exponent: ");
        int exponent = scanner.nextInt();
        double result = Math.pow(base, exponent);
        System.out.println(base + "^" + exponent + " = " + result);
    }
}

Explanation:

The program first creates a Scanner object to read user input from the console. It then prompts the user to enter the base number and exponent by printing the messages "Enter the base number: " and "Enter the exponent: " to the console.

The nextDouble and nextInt methods of the Scanner object are called to read the next double and integer values entered by the user and store them in the base and exponent variables, respectively.

The program then calls the Math.pow method to calculate the power of the base number raised to the exponent. The result is stored in the result variable.

The program then prints the result to the console.

Note that the Math.pow method returns a double value, which is why the base variable is also declared as a double. If you need to calculate the power of two integer values and return an integer result, you could write your own function to calculate the power of a number using repeated multiplication, as shown in other examples in this thread.