java how to find power of a number without using pow function code example

Example 1: Java program to find the power of a number

@Test
	public void powerOfTheNumberProgram13() {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter any NUMBER: ");
		int number = scanner.nextInt();
		System.out.println("Enter the POWER: ");
		int power = scanner.nextInt();
		scanner.close();
		// Logic for finding the POWER of number
		int powerOfNumber = (int) Math.pow(number, power);
		System.out.println("Power of a " + number + "^" + power + ": " + powerOfNumber);
	}

Example 2: Write a method that raises a number to a power without using Math.pow() method

public class Power {

    public static void main(String[] args) {

        int base = 3, exponent = 4;

        long result = 1;

        while (exponent != 0)
        {
            result *= base;
            --exponent;
        }

        System.out.println("Answer = " + result);
    }
}

Tags:

Java Example