|
-
Oct 25th, 2006, 01:15 PM
#1
Thread Starter
Junior Member
Can somebody help me finish this
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 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 = 1
2^1 = 2
2^2 = 4
2^3 = 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
System.out.println("Here are the first " + numPowersOf2 + " powers of 2: ");
//initialize exponent -- the first thing printed is 2 to the what?
exponent = 0;
while (exponent < numPowersOf2);
{
//print out current power of 2
System.out.println("2^" + -- exponent + " = " + nextPowerOf2);
//find next power of 2 -- how do you get this from the last one?
nextPowerOf2 = nextPowerOf2 * 2;
//increment exponent
exponent++;
}
}
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|