C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Find result of power without Math.pow() - Java Program

Below is a Java program to calculate the power of a number without using Math.pow(), along with sample outputs and a step-by-step explanation.

We will calculate baseexponent using a loop.

 

import java.util.Scanner;

 

public class PowerWithoutMath {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

 

        // Taking input

        System.out.print("Enter the base number: ");

        double base = sc.nextDouble();

 

        System.out.print("Enter the exponent (non-negative integer): ");

        int exponent = sc.nextInt();

 

        double result = 1;

 

        // Calculating power using loop

        for (int i = 1; i <= exponent; i++) {

            result *= base;  // Multiply base exponent times

        }

 

        // Displaying result

        System.out.println(base + " raised to the power " + exponent + " = " + result);

 

        sc.close();

    }

}

Output

 
OUTPUT 1:
Enter the base number: 2
Enter the exponent (non-negative integer): 5
2.0 raised to the power 5 = 32.0

OUTPUT 2:
Enter the base number: 3
Enter the exponent (non-negative integer): 4
3.0 raised to the power 4 = 81.0

Explanation

Step 1: Input

double base = sc.nextDouble();

int exponent = sc.nextInt();

  • Base can be a decimal
  • Exponent must be a non-negative integer

Step 2: Initialize result

double result = 1;

Start with 1 because multiplying by 1 doesn’t change the value.

Step 3: Multiply in a loop

for (int i = 1; i <= exponent; i++) {

    result *= base;

}

  • Loop runs exponent times
  • Each iteration multiplies result by base
  • After loop: result = base^exponent

Step 4: Display result

System.out.println(base + " raised to the power " + exponent + " = " + result);

Prints the final calculated value.