Tuan Nguyen - 7 months ago 64

Java Question

I'm writing a simple program to calculate power of 2. A user would enter the number of times they want to calculate the power of 2, let say the user enter 4, my program would returns 2,4,8,16.Here is the code

`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 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?

System.out.println("Here are the first " + numPowersOf2 + " power of 2");

while (exponent<numPowersOf2)

{

//print out current power of 2

nextPowerOf2=nextPowerOf2*2;

exponent++;

System.out.println(nextPowerOf2);

//find next power of 2 -- how do you get this from the last one?

//increment exponent

}

}

}

If I want it to start at 0 first say like 2^0=1, so if user enter 4, it would give back 1,2,4,8 instead of 2,4,8,16. How do I modify this to get that?

Answer

Just print `nextPowerOf2`

before you change it.

```
while (exponent<numPowersOf2)
{
System.out.println(nextPowerOf2);
nextPowerOf2=nextPowerOf2*2;
exponent++;
}
```