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
- Read the base
xand the exponentyfrom the user. - Initialize a variable
resto 1. - Start a
forloop from 1 toy. - In each iteration, multiply
resbyx(res = res * x). - 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
resbyxfor a total ofytimes. - 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
resto 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.