Power of a number

The power of a number represents the number of times to use that number in a multiplication. Usually, power is represented with a base number and an exponent.

Logic

Let’s declare one temporary variable power with value 1, we have used the data-type long so that it can hold a big long value.

To calculate the power of a number we need a base and an exponent value, we are taking these two values from the user, after taking input (base, exponent) from the user we start one loop from 1 to exponent.

Inside the loop, for every iteration, we multiply the base by power (base * power) and store the result again in variable power until the loop is completed.

Once the loop is over, simply print the variable power containing the resultant power value of a given number.

Program

import java.util.Scanner;

public class FindPower {
    
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // Take input from user
        System.out.print("Enter base and exponent : ");
        int base = scanner.nextInt();
        int exponent = scanner.nextInt();

        long power = 1;

        // Multiply base, exponent times
        for(int i = 1; i <= exponent; i++) {
            power = power * base;
        }

        System.out.println("\nResult " + base + " ^ " + exponent + " : " + power);
        System.out.println("Using Math class : " + Math.pow(base, exponent));
    }

}

Output

Enter base and exponent :
Result 2 ^ 5 : 32
Using Math class : 32.0