Spaces:
Running
Running
Create 19. Smaller powers of two
Browse files
Week 1: Types, condition clauses and loops/19. Smaller powers of two
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Write a program that asks the user to enter an integer.
|
| 2 |
+
The program prints the powers of two that are less than the upper limit given.
|
| 3 |
+
In practice, the program prints numbers from the series 1, 2, 4, 8...etc.
|
| 4 |
+
|
| 5 |
+
Example execution:
|
| 6 |
+
Give the upper limit: 25
|
| 7 |
+
1
|
| 8 |
+
2
|
| 9 |
+
4
|
| 10 |
+
8
|
| 11 |
+
16
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
===================
|
| 16 |
+
|
| 17 |
+
import java.util.Random;
|
| 18 |
+
import java.util.Scanner;
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
public class Test{
|
| 23 |
+
public static void main(String[] args){
|
| 24 |
+
final Random r = new Random();
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
Scanner reader= new Scanner(System.in);
|
| 28 |
+
System.out.print("Give the upper limit: ");
|
| 29 |
+
int upperLimit = Integer.valueOf(reader.nextLine());
|
| 30 |
+
|
| 31 |
+
int num = 1;
|
| 32 |
+
while (num < upperLimit) {
|
| 33 |
+
System.out.println(num);
|
| 34 |
+
num = num * 2;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
Test number 1
|
| 49 |
+
Give the upper limit: 25
|
| 50 |
+
1
|
| 51 |
+
2
|
| 52 |
+
4
|
| 53 |
+
8
|
| 54 |
+
16
|
| 55 |
+
|
| 56 |
+
Test number 2
|
| 57 |
+
Give the upper limit: 100
|
| 58 |
+
1
|
| 59 |
+
2
|
| 60 |
+
4
|
| 61 |
+
8
|
| 62 |
+
16
|
| 63 |
+
32
|
| 64 |
+
64
|
| 65 |
+
|
| 66 |
+
Test number 3
|
| 67 |
+
Give the upper limit: 129
|
| 68 |
+
1
|
| 69 |
+
2
|
| 70 |
+
4
|
| 71 |
+
8
|
| 72 |
+
16
|
| 73 |
+
32
|
| 74 |
+
64
|
| 75 |
+
128
|
| 76 |
+
|
| 77 |
+
Test number 4
|
| 78 |
+
Give the upper limit: 33
|
| 79 |
+
1
|
| 80 |
+
2
|
| 81 |
+
4
|
| 82 |
+
8
|
| 83 |
+
16
|
| 84 |
+
32
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
|