File PowersOf2.java contains a skeleton of a program to read in an integer from
ID: 3621307 • Letter: F
Question
File 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 numbe rof powers of 2 that the user requests. Do not use Math.pow to complete 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
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 = 1
2^1 = 2
2^2 = 4
2^3 = 8
Explanation / Answer
Hope this helps. Please rate. :) import java.io.BufferedReader; import java.io.InputStreamReader; public class Powers { public static void main(String[] args) { int n = 0; int pow = 1; BufferedReader bin = new BufferedReader( new InputStreamReader(System.in)); try { System.out.print("Enter a positive integer: "); n = Integer.parseInt(bin.readLine()); } catch (Exception e) { e.printStackTrace(); } System.out.println("Here are the first " + n + " powers of 2"); for (int i = 0; iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.