Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find x to the power y (xy) using loop.

Java Code Example — Simple Programs

ADVERTISEMENT

Java Program to find x to the power y (xy) using loop.

Objective

Write a Java program to calculate a base number raised to a power using a simple loop.

Algorithm / Approach

  1. Read the base x and the exponent y from the user.
  2. Initialize a variable res to 1.
  3. Start a for loop from 1 to y.
  4. In each iteration, multiply res by x (res = res * x).
  5. After the loop completes, print the result.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Base: ");
  int x = s.nextInt();
  System.out.print("Enter Power: ");
  int y = s.nextInt();
  int res = 1;
  for(int i = 1; i<=y; i++) {
   res = res*x;
  }
  System.out.print("Result = "+res);
 }
}

Expected Output

Enter Base: 5
Enter Power: 4
Result = 625

Explanation of the Program

  • Exponentiation simply means multiplying a base number by itself a specific number of times.
  • The loop acts as a manual multiplier, multiplying the accumulator res by x for a total of y times.
  • The accumulator is initialized to 1 because 1 is the multiplicative identity. Any number multiplied by 1 is itself.

Complexity

Time Complexity O(y) - The loop iterates exactly y times.
Space Complexity O(1)

Common Mistakes

  • Initializing res to 0 instead of 1, resulting in an answer of 0 for every calculation.
  • Handling negative exponents. This specific algorithm assumes the power is a positive integer.
ADVERTISEMENT