Power of Number
Compute a^b using a loop (similar to earlier power program).
BeginnerTopic: Module 3: Loop Programs
Java Power of Number Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter base: ");
int a = sc.nextInt();
System.out.print("Enter exponent: ");
int b = sc.nextInt();
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
System.out.println(a + " ^ " + b + " = " + result);
sc.close();
}
}Output
Enter base: 3 Enter exponent: 4 3 ^ 4 = 81
Understanding Power of Number
We multiply the base by itself b times; demonstrates loop-based exponentiation.
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.