Skip to content

Commit 646fa6f

Browse files
committed
one more bug in 4-5
1 parent 2fd3037 commit 646fa6f

1 file changed

Lines changed: 4 additions & 3 deletions

File tree

_sources/Unit4-Iteration/topic-4-5-loop-analysis.rst

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ This code will print a triangle of stars instead of a rectangle because the inne
282282
:language: java
283283
:autograde: unittest
284284

285-
How many stars are printed out by the following non-rectangular loops? Trace through it with the Code Lens button. Then, can you change the code so that the triangle is upside down where the first row has 5 stars and the last row has 1 star? Hint: make the inner loop count backwards from i to 0.
285+
How many stars are printed out by the following non-rectangular loops? Trace through it with the Code Lens button. Then, can you change the code so that the triangle is upside down where the first row has 5 stars and the last row has 1 star? Hint: make the inner loop count from row up to 5.
286286
~~~~
287287
public class NestedLoops
288288
{
@@ -291,7 +291,7 @@ This code will print a triangle of stars instead of a rectangle because the inne
291291
{
292292
for (int row = 0; row < 5; row++)
293293
{
294-
// Change the inner loop to count backwards from i to 0
294+
// Change the inner loop to count from row up to 5
295295
for (int col = 0; col <= row; col++)
296296
{
297297
System.out.print("*");
@@ -320,11 +320,12 @@ This code will print a triangle of stars instead of a rectangle because the inne
320320
@Test
321321
public void testCodeContains()
322322
{
323-
boolean check = checkCodeContains("col=i", "col=i");
323+
boolean check = checkCodeContains("col=row", "col=row");
324324
assertTrue(check);
325325
}
326326
}
327327

328+
328329
How many stars are printed out? How many times do the loops iterate? The outer loop runs 5 times and the inner loop runs 0, 1, 2, 3, 4, 5 times respectively. So, the number of stars printed are 0 + 1 + 2 + 3 + 4 + 5 = 15. Notice that this is the sum of a series of natural numbers from 0 to 5.
329330

330331
There is a neat formula to calculate the sum of n natural numbers: ``n(n+1)/2`` where n is the number of times the outer loop runs or the maximum number of times the inner loop runs. So, for the example above, the outer loop runs 5 times (and the inner loop runs 0 to a maximum of 5 times) so for n=5, the inner loop runs 5(5+1)/2 = 15 times.

0 commit comments

Comments
 (0)