32 lines
1003 B
Plaintext
32 lines
1003 B
Plaintext
// WHILE LOOP
|
|
import java.util.Scanner;
|
|
|
|
public class PowersOf2
|
|
{
|
|
public static void main(String[] args)
|
|
{
|
|
int numPowersOf2; // How many powers of 2 to compute
|
|
int nextPowerOf2 = 1; // Current power of 2 (starting with 2^0 = 1)
|
|
int exponent = 0; // Exponent for current power of 2 (starting with 0)
|
|
Scanner scan = new Scanner(System.in);
|
|
|
|
System.out.println("How many powers of 2 would you like printed?");
|
|
numPowersOf2 = scan.nextInt();
|
|
|
|
// Print a message saying how many powers of 2 will be printed
|
|
System.out.println("Here are the first " + numPowersOf2 + " powers of 2:");
|
|
|
|
// Print the powers of 2
|
|
while (exponent < numPowersOf2)
|
|
{
|
|
System.out.println("2^" + exponent + " = " + nextPowerOf2);
|
|
|
|
// Compute the next power of 2 by doubling the current one
|
|
nextPowerOf2 *= 2;
|
|
|
|
// Increment exponent
|
|
exponent++;
|
|
}
|
|
}
|
|
}
|