Power without Math.pow()

Compute a^b using a loop instead of Math.pow().

BeginnerTopic: Module 1: Basic Java Programs
Back

Java Power without Math.pow() Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter base (a): ");
        int a = sc.nextInt();
        System.out.print("Enter exponent (b): ");
        int b = sc.nextInt();

        long result = 1;
        for (int i = 1; i <= b; i++) {
            result *= a;
        }

        System.out.println(a + " raised to " + b + " = " + result);

        sc.close();
    }
}
Output
Enter base (a): 2
Enter exponent (b): 5
2 raised to 5 = 32

Understanding Power without Math.pow()

We multiply the base by itself b times in a loop to compute a^b.

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents