Advertisement
cgorrillaha

Untitled

Nov 20th, 2020
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. // ****************************************************************
  2. //   PowersOf2.java
  3. //
  4. //   Print out as many powers of 2 as the user requests
  5. //
  6. // ****************************************************************
  7. import java.util.Scanner;
  8.  
  9. public class PowersOf2
  10. {
  11.     public static void main(String[] args)
  12.     {
  13.         int numPowersOf2;        //How many powers of 2 to compute
  14.         int nextPowerOf2 = 1;    //Current power of  2
  15.         int exponent=1;            //Exponent for current power of 2 -- this
  16.         //also serves as a counter for the loop
  17.         Scanner scan = new Scanner(System.in);
  18.  
  19.         System.out.println("How many powers of 2 would you like printed?");
  20.         numPowersOf2 = scan.nextInt();
  21.  
  22.         //print a message saying how many powers of 2 will be printed
  23.         //initialize exponent -- the first thing printed is 2 to the what?
  24.  
  25.         while (exponent<=numPowersOf2)
  26.         {
  27.             //print out current power of 2
  28.             nextPowerOf2=nextPowerOf2*2;
  29.             System.out.println("2^"+exponent+" = "+nextPowerOf2);
  30.             exponent++;
  31.         }
  32.     }
  33. }
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement