Repository navigation
Expand file tree
/
Copy pathch5_loopsanditeration.ptx
More file actions
327 lines (292 loc) · 11.5 KB
/
Copy pathch5_loopsanditeration.ptx
File metadata and controls
327 lines (292 loc) · 11.5 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
<?xml version="1.0"?>
<chapter xml:id="loops-and-iteration">
<title>Loops and Iteration</title>
<section xml:id="definite-loop">
<title>Definite Loop</title>
<p>
You have already seen a couple of examples of iteration and looping in Java.
So this section will just serve as a reference for the differences in syntax.
</p>
<p><idx><c>for</c> loop</idx>
A <term>definite loop</term> is a loop that is executed a specific or definite number of times. In Python, the easiest way to write a definite loop is using the <c>for</c> loop in conjunction with the <c>range</c> function.
For example:
</p>
<program interactive="activecode" language="python">
<code>
for i in range(10):
print(i)
</code>
</program>
<p>
In Java, we would write this as:
</p>
<program interactive="activecode" language="java">
<code>
public class DefiniteLoopExample {
public static void main(String[] args) {
for (Integer i = 0; i < 10; i++ ) {
System.out.println(i);
}
}
}
</code>
</program>
<p>
Recall that the <c>range</c> function provides you with a wide variety of options for controlling the value of the loop variable.
</p>
<pre>
range(stop)
range(start,stop)
range(start,stop,step)
</pre>
<p>
The Java <c>for</c> loop is really analogous to the last option giving you explicit control over the starting, stopping, and stepping in the three clauses inside the parenthesis.
You can think of it this way:
</p>
<pre>
for (start clause; stop clause; step clause) {
statement1
statement2
...
}
</pre>
<p>
If you want to start at 100, stop at 0 and count backward by 5, the Python loop would be written as:
</p>
<program interactive="activecode" language="python">
<code>
for i in range(100, -1, -5):
print(i)
</code>
</program>
<p>
In Java, we would write this as:
</p>
<program interactive="activecode" language="java">
<code>
public class DefiniteLoopBackward {
public static void main(String[] args) {
for (Integer i = 100; i >= 0; i -= 5) {
System.out.println(i);
}
}
}
</code>
</program>
<p>
In Python, the <c>for</c> loop can also iterate over any sequence such as a list, a string, or a tuple.
Java also provides a variation of its <c>for</c> loop that provides the same functionality in its so-called for each loop.
</p>
<p>
In Python, we can iterate over a list as follows:
</p>
<program interactive="activecode" language="python">
<code>
l = [1, 1, 2, 3, 5, 8, 13, 21]
for fib in l:
print(fib)
</code>
</program>
<p>
In Java we can iterate over an <c>ArrayList</c> of integers too. Note that this requires importing the <c>ArrayList</c> class.
</p>
<program interactive="activecode" language="java">
<code>
import java.util.ArrayList;
public class ForEachArrayListExample {
public static void main(String[] args) {
ArrayList<Integer> l = new ArrayList<Integer>();
l.add(1);
l.add(1);
l.add(2);
l.add(3);
l.add(5);
l.add(8);
l.add(13);
l.add(21);
for (Integer i : l) {
System.out.println(i);
}
}
}
</code>
</program>
<p>
This example stretches the imagination a bit, and in fact points out one area where Java's primitive arrays are easier to use than an array list.
In fact all primitive arrays can be used in a for each loop.
</p>
<program interactive="activecode" language="java">
<code>
public class ForEachArrayExample {
public static void main(String[] args) {
int l[] = {1,1,2,3,5,8,13,21};
for(int i : l) {
System.out.println(i);
}
}
}
</code>
</program>
<p>
To iterate over the characters in a string in Java do the following:
</p>
<program interactive="activecode" language="java">
<code>
public class StringIterationExample {
public static void main(String[] args) {
String t = "Hello World";
for (char c : t.toCharArray()) {
System.out.println(c);
}
}
}
</code>
</program>
</section>
<section xml:id="indefinite-loops">
<title>Indefinite Loops</title>
<p><idx><c>while</c> loop</idx>
Both Python and Java support the <c>while</c> loop, which continues to execute as long as a condition is true.
Here is a simple example in Python that counts down from 5:
</p>
<program interactive="activecode" language="python">
<code>
i = 5
while i > 0:
print(i)
i = i - 1
</code>
</program>
<p>
In Java we add parenthesis and curly braces. Here is the same countdown loop in Java:
</p>
<program interactive="activecode" language="java">
<code>
public class WhileLoopExample {
public static void main(String[] args) {
int i = 5;
while (i > 0) {
System.out.println(i);
i = i - 1;
}
}
}
</code>
</program>
<p><idx><c>do-while</c> loop</idx>
Java adds an additional, if seldom used variation of the <c>while</c> loop called the <c>do-while</c> loop.
The <c>do-while</c> loop is very similar to <c>while</c> except that the condition is evaluated at the end of the loop rather than the beginning.
This ensures that a loop will be executed at least one time.
Some programmers prefer this loop in some situations because it avoids an additional assignment prior to the loop.
For example, the following loop will execute once even though the condition is initially false.
</p>
<program interactive="activecode" language="java">
<code>
public class DoWhileExample {
public static void main(String[] args) {
int i = 10;
do {
System.out.println("This runs once, i = " + i);
} while (i < 5);
}
}
</code>
</program>
</section>
<section xml:id="chapter5_summary">
<title>Summary & Reading Questions</title>
<p>
<ol label="1">
<li>
<p>Java’s <c>for</c> loop syntax allows you to control loop initialization, condition, and update in one line using the format <c>for (init; condition; update)</c>.</p>
</li>
<li>
<p>To loop over lists or arrays in Java, the enhanced for-each loop uses the syntax <c>for (type var : collection)</c>, which is similar to Python’s <c>for item in list</c>.</p>
</li>
<li>
<p>Python’s <c>range()</c> function supports start, stop, and step, which directly maps to the three components of a Java <c>for</c> loop.</p>
</li>
<li>
<p>Java also supports the <c>while</c> loop, which executes a block of code while a condition is true, similar to Python’s <c>while</c> loop.</p>
</li>
<li>
<p>Java’s <c>do-while</c> loop guarantees the loop body executes at least once, because the condition is evaluated after the loop body.</p>
</li>
<li>
<p>To iterate through characters in a Java String, use <c>toCharArray()</c> along with a for-each loop.</p>
</li>
</ol>
</p>
<reading-questions xml:id="rqs-5">
<exercise label="summary-for-loop-structure">
<statement>
<p>Which of the following is the correct format for a definite loop in Java that runs 10 times?</p>
</statement>
<choices>
<choice>
<statement><p>for i in range(10):</p></statement>
<feedback><p>No, that is Python syntax.</p></feedback>
</choice>
<choice correct="yes">
<statement><p>for (int i = 0; i < 10; i++)</p></statement>
<feedback><p>Correct! That’s the proper Java syntax for a definite loop.</p></feedback>
</choice>
<choice>
<statement><p>loop i from 0 to 10</p></statement>
<feedback><p>No, this is not valid syntax in Java.</p></feedback>
</choice>
<choice>
<statement><p>for (i < 10; i++)</p></statement>
<feedback><p>No, the initialization part is missing in this Java loop.</p></feedback>
</choice>
</choices>
</exercise>
<exercise label="summary-for-each-array">
<statement>
<p>Which loop correctly iterates through all elements in a Java array of integers?</p>
</statement>
<choices>
<choice correct="yes">
<statement><p>for (int i : array)</p></statement>
<feedback><p>Yes! This is Java's enhanced for-each loop for arrays.</p></feedback>
</choice>
<choice>
<statement><p>for (i in array)</p></statement>
<feedback><p>No, that's closer to Python syntax.</p></feedback>
</choice>
<choice>
<statement><p>for (int i = 0; i < array; i++)</p></statement>
<feedback><p>No, <c>array</c> is not a valid condition; use <c>array.length</c>.</p></feedback>
</choice>
<choice>
<statement><p>foreach i in array:</p></statement>
<feedback><p>No, this is not valid Java syntax.</p></feedback>
</choice>
</choices>
</exercise>
<exercise label="summary-do-while">
<statement>
<p>What is a unique characteristic of the Java <c>do-while</c> loop compared to the <c>while</c> loop?</p>
</statement>
<choices>
<choice>
<statement><p>It checks the condition before the loop body runs.</p></statement>
<feedback><p>No, that describes a regular <c>while</c> loop.</p></feedback>
</choice>
<choice>
<statement><p>It always runs infinitely.</p></statement>
<feedback><p>No, a <c>do-while</c> loop will stop when its condition becomes false.</p></feedback>
</choice>
<choice correct="yes">
<statement><p>It guarantees the loop body runs at least once.</p></statement>
<feedback><p>Correct! The <c>do-while</c> loop checks the condition after running the loop body.</p></feedback>
</choice>
<choice>
<statement><p>It is not supported in Java.</p></statement>
<feedback><p>No, Java does support <c>do-while</c> loops.</p></feedback>
</choice>
</choices>
</exercise>
</reading-questions>
</section>
</chapter>