Powers of 2 File PowersOf2.java contains a skeleton of a program to read in an i
ID: 3641635 • Letter: P
Question
Powers of 2File PowersOf2.java contains a skeleton of a program to read in an integer from the user and print out that many powers of 2,
starting with 20.
1.
Using the comments as a guide, complete the program so that it prints out the number of powers of 2 that the user
requests. Do not use Math.pow to compute the powers of 2! Instead, compute each power from the previous one (how
do you get 2n from 2n–1?). For example, if the user enters 4, your program should print this:
Here are the first 4 powers of 2:
1
2
4
8
2.
Modify the program so that instead of just printing the powers, you print which power each is, e.g.:
Here are the first 4 powers of 2:
2^0
2^1
2^2
2^3
=
=
=
=
1
2
4
8
// ************************************************************
//
PowersOf2.java
//
//
Print out as many powers of 2 as the user requests
//
// ************************************************************
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
int exponent;
//Exponent for current power of 2 -- this
//also serves as a counter for the loop 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
//initialize exponent -- the first thing printed is 2 to the what?
while ( )
{
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent
}
}
}
Explanation / Answer
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
int exponent = 0;
//Exponent for current power of 2 -- this
//also serves as a counter for the loop Scanner
Scanner scan = new Scanner(System.in);
System.out.print("How many powers of 2 would you like printed? ");
numPowersOf2 = scan.nextInt();
//print a message saying how many powers of 2 will be printed
//initialize exponent -- the first thing printed is 2 to the what?
while(exponent < numPowersOf2) {
//print out current power of 2
//find next power of 2 -- how do you get this from the last one?
//increment exponent
System.out.println("2^" + exponent + " = " + nextPowerOf2);
nextPowerOf2 = 2* nextPowerOf2;
exponent++;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.