Repository navigation
Expand file tree
/
Copy pathch5_loopsanditeration.ptx
More file actions
454 lines (419 loc) · 17.5 KB
/
Copy pathch5_loopsanditeration.ptx
File metadata and controls
454 lines (419 loc) · 17.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
<?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>
<idx>definite loop</idx>
A <term>definite loop</term>, also known as a <term><c>for</c> loop</term>, is a loop that is executed for a specific or <em>definite</em> number of times. In Python, the easiest way to write a definite loop is using the <c>for</c> loop structure in conjunction with the <c>range</c> function. <xref ref="python-range-options" text="type-global"/> shows the syntax for the <c>range</c> function.
</p>
<listing xml:id="python-definite-loop">
<program interactive="activecode" language="python">
<code>
for i in range(10): # range(10) is a list of integers from 0 to 9
print(i)
</code>
</program>
</listing>
<p>
<xref ref="java-definite-loop" text="type-global"/> shows how the <c>for</c> loop is written in Java.
</p>
<listing xml:id="java-definite-loop">
<program interactive="activecode" language="java">
<code>
public class DefiniteLoopExample {
public static void main(String[] args) {
for (Integer i = 0; i < 10; i++ ) { // notice how the initialization, condition, and update are all on the same line.
System.out.println(i);
}
}
}
</code>
</program>
</listing>
<p>
Recall that the <c>range</c> function provides you with a wide variety of options for controlling the value of the loop variable as shown in <xref ref="python-range-options" text="type-global"/>.
</p>
<listing xml:id="python-range-options">
<program>
<code>
range(stop)
range(start,stop)
range(start,stop,step)
</code>
</program>
</listing>
<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.
<xref ref="java-for-loop-syntax" text="type-global"/> shows how the Java <c>for</c> loop is written.
</p>
<listing xml:id="java-for-loop-syntax">
<program>
<code>
for (start clause; stop clause; step clause) {
statement1
statement2
...
}
</code>
</program>
</listing>
<p>
If you want to start at 100, stop at 0 and count backward by 5, <xref ref="python-definite-decrement" text="type-global"/> shows how the Python <c>for</c> loop is written.
</p>
<listing xml:id="python-definite-decrement">
<program interactive="activecode" language="python">
<code>
for i in range(100, -1, -5): # start at 100, stop at 0, decrement by 5
print(i)
</code>
</program>
</listing>
<p>
<xref ref="java-definite-decrement" text="type-global"/> shows how the <c>for</c> loop is written in Java.
</p>
<listing xml:id="java-definite-decrement">
<program interactive="activecode" language="java">
<code>
public class DefiniteLoopBackward {
public static void main(String[] args) {
for (Integer i = 100; i >= 0; i -= 5) { // start at 100, stop at 0, decrement by 5
System.out.println(i);
}
}
}
</code>
</program>
</listing>
<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>
<xref ref="python-list-iteration" text="type-global"/> shows how the <c>for</c> loop can be used to iterate over a list in Python.
</p>
<listing xml:id="python-list-iteration">
<program interactive="activecode" language="python">
<code>
l = [1, 1, 2, 3, 5, 8, 13, 21] # create a list of integers
for fib in l: # iterate over the list
print(fib)
</code>
</program>
</listing>
<p>
<xref ref="java-list-iteration" text="type-global"/> shows how the <c>for</c> loop can be used to iterate over an <c>ArrayList</c> of integers in Java.
</p>
<listing xml:id="java-list-iteration">
<program interactive="activecode" language="java">
<code>
import java.util.ArrayList;
public class ForEachArrayListExample {
public static void main(String[] args) {
ArrayList<Integer> l = new ArrayList< // create an ArrayList of integers
l.add(1); // add the first integer to the list
l.add(1); // add the second integer to the list
l.add(2); // keep going
l.add(3);
l.add(5);
l.add(8);
l.add(13);
l.add(21); // add the last integer to the list
for (Integer i : l) { // iterate over the list
System.out.println(i);
}
}
}
</code>
</program>
</listing>
<p>
<xref ref="java-list-iteration" text="type-global"/> 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.
<xref ref="java-for-each" text="type-global"/> shows how the <c>for</c> loop can be used to iterate over all elements in a primitive array in Java.
</p>
<listing xml:id="java-for-each">
<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}; // create an array of integers using primitive syntax
for(int i : l) { // iterate over the array
System.out.println(i);
}
}
}
</code>
</program>
</listing>
<p>
<xref ref="java-for-each" text="type-global"/> shows how the <c>for</c> loop can be used to iterate over all elements in a string in Java.
</p>
<listing xml:id="java-string-iteration">
<program interactive="activecode" language="java">
<code>
public class StringIterationExample {
public static void main(String[] args) {
String t = "Hello World"; // create a string
for (char c : t.toCharArray()) { // iterate over the characters in the string
System.out.println(c);
}
}
}
</code>
</program>
</listing>
<exercise label="java_loops_sum_evens_parsons">
<statement>
<p>
Rearrange the blocks to create a Java method that accepts an upper bound integer <c>limit</c> and calculates the sum of all even numbers from 2 up to and including <c>limit</c>.
</p>
</statement>
<blocks>
<block order="1">
<cline>public int sumEvens(int limit) {</cline>
</block>
<block order="2">
<choice correct="yes">
<cline> int total = 0;</cline>
</choice>
<choice correct="no">
<cline> int total;</cline>
</choice>
</block>
<block order="3">
<choice correct="yes">
<cline> for (int i = 2; i <= limit; i += 2) {</cline>
</choice>
<choice correct="no">
<cline> for (int i = 2; i < limit; i =+ 2) {</cline>
</choice>
</block>
<block order="4">
<choice correct="yes">
<cline> total += i;</cline>
<cline> }</cline>
</choice>
<choice correct="no">
<cline> total = i;</cline>
<cline> }</cline>
</choice>
</block>
<block order="5">
<choice correct="yes">
<cline> return total;</cline>
<cline>}</cline>
</choice>
<choice correct="no">
<cline> return i;</cline>
<cline>}</cline>
</choice>
</block>
</blocks>
</exercise>
</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.
<xref ref="python-countdown" text="type-global"/> shows a simple example in Python that counts down from 5.
</p>
<listing xml:id="python-countdown">
<program interactive="activecode" language="python">
<code>
i = 5
while i > 0: # while i is greater than 0
print(i)
i = i - 1
</code>
</program>
</listing>
<p>
In Java, we add parentheses and curly braces. <xref ref="java-countdown" text="type-global"/> shows the same countdown loop in Java.
</p>
<listing xml:id="java-countdown">
<program interactive="activecode" language="java">
<code>
public class WhileLoopExample {
public static void main(String[] args) {
int i = 5;
while (i > 0) { // while i is greater than 0
System.out.println(i);
i = i - 1;
}
}
}
</code>
</program>
</listing>
<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, <xref ref="java-do-while" text="type-global"/> shows how loop will execute once even though the condition is initially false.
</p>
<listing xml:id="java-do-while">
<program interactive="activecode" language="java">
<code>
public class DoWhileExample {
public static void main(String[] args) {
int i = 10;
do { // do-while loop, will run at least once no matter the condition
System.out.println("This runs once, i = " + i);
} while (i < 5); // while i is less than 5
}
}
</code>
</program>
</listing>
<exercise label="java_loops_indefinite_parsons">
<statement>
<p>
Rearrange the blocks to create a Java method that accepts a starting balance and a target amount, then calculates how many years it takes for the balance to reach or exceed the target by doubling each year.
</p>
</statement>
<blocks>
<block order="1">
<choice correct="yes">
<cline>public int yearsToTarget(double balance, double target) {</cline>
<cline> int years = 0;</cline>
</choice>
<choice correct="no">
<cline>public int yearsToTarget(double balance, double target) {</cline>
<cline> int years;</cline>
</choice>
</block>
<block order="2">
<choice correct="yes">
<cline> while (balance < target) {</cline>
</choice>
<choice correct="no">
<cline> while (balance >= target) {</cline>
</choice>
</block>
<block order="3">
<choice correct="yes">
<cline> balance *= 2;</cline>
<cline> years++;</cline>
<cline> }</cline>
</choice>
<choice correct="no">
<cline> balance * 2;</cline>
<cline> years++;</cline>
<cline> }</cline>
</choice>
</block>
<block order="4">
<choice correct="yes">
<cline> return years;</cline>
<cline>}</cline>
</choice>
<choice correct="no">
<cline> return balance;</cline>
<cline>}</cline>
</choice>
</block>
</blocks>
</exercise>
</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>