Calculate the Power of a Number using a For Loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Power { | |
public static void main(String[] args) { | |
int base = 3, exponent = 3; | |
long result = 1; | |
for (int i = 0; i < exponent; i++) { | |
result *= base; | |
} | |
System.out.println(base + " to the power of " + exponent + " is equal to " + result); | |
} | |
} |
When you run the program, the output will be:
3 to the power of 3 is equal to 27
Calculate the Power of a Number using a While Loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Power { | |
public static void main(String[] args) { | |
int base = 3, exponent = 3; | |
int i = 0; | |
long result = 1; | |
while (i < exponent) { | |
result *= base; | |
i++; | |
} | |
System.out.println(base + " to the power of " + exponent + " is equal to " + result); | |
} | |
} |
When you run the program, the output will be:
2 to the power of 5 is equal to 32
إرسال تعليق
Thank you for vising