assignment4
This commit is contained in:
31
labs/lab5/WHILE LOOP.txt
Normal file
31
labs/lab5/WHILE LOOP.txt
Normal file
@ -0,0 +1,31 @@
|
||||
// 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++;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user