Advertisement
Goude

Untitled

Oct 8th, 2015
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 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 = 0; //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. System.out.println("Okay, I will print " + numPowersOf2 + " powers of two.");
  24.  
  25.  
  26. do
  27. {
  28. //print out current power of 2
  29. System.out.println(2 + "^" + exponent + " = " + nextPowerOf2);
  30.  
  31. //find next power of 2 -- how do you get this from the last one?
  32. nextPowerOf2 *= 2;
  33.  
  34. //increment exponent
  35. exponent += 1;
  36.  
  37. } while (exponent != numPowersOf2);
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement