forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoops.java
More file actions
89 lines (74 loc) · 1.98 KB
/
Loops.java
File metadata and controls
89 lines (74 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Demonstrates uses of loops.
*/
public class Loops {
public static void countdown(int n) {
while (n > 0) {
System.out.println(n);
n = n - 1;
}
System.out.println("Blastoff!");
}
public static void sequence(int n) {
while (n != 1) {
System.out.println(n);
if (n % 2 == 0) { // n is even
n = n / 2;
} else { // n is odd
n = n * 3 + 1;
}
}
}
public static void plusplus() {
int i = 1;
while (i <= 5) {
System.out.println(i);
i++; // add 1 to i
}
}
public static void appreciate() {
int i = 2;
while (i <= 8) {
System.out.print(i + ", ");
i += 2; // add 2 to i
}
System.out.println("Who do we appreciate?");
}
public static void appreciate2() {
for (int i = 2; i <= 8; i += 2) {
System.out.print(i + ", ");
}
System.out.println("Who do we appreciate?");
}
public static void loopvar() {
int n;
for (n = 3; n > 0; n--) {
System.out.println(n);
}
System.out.println("n is now " + n);
}
public static void nested() {
for (int x = 1; x <= 10; x++) {
for (int y = 1; y <= 10; y++) {
System.out.printf("%4d", x * y);
}
System.out.println();
}
}
public static void main(String[] args) {
System.out.println("\ncountdown");
countdown(3);
System.out.println("\nsequence");
sequence(10);
System.out.println("\nplusplus");
plusplus();
System.out.println("\nappreciate");
appreciate();
System.out.println("\nappreciate2");
appreciate2();
System.out.println("\nloopvar");
loopvar();
System.out.println("\nnested");
nested();
}
}