Skip to content

Commit

Permalink
one more bug in 4-5
Browse files Browse the repository at this point in the history
  • Loading branch information
bhoffman0 committed Nov 11, 2024
1 parent 2fd3037 commit 646fa6f
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions _sources/Unit4-Iteration/topic-4-5-loop-analysis.rst
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ This code will print a triangle of stars instead of a rectangle because the inne
:language: java
:autograde: unittest

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.
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.
~~~~
public class NestedLoops
{
Expand All @@ -291,7 +291,7 @@ This code will print a triangle of stars instead of a rectangle because the inne
{
for (int row = 0; row < 5; row++)
{
// Change the inner loop to count backwards from i to 0
// Change the inner loop to count from row up to 5
for (int col = 0; col <= row; col++)
{
System.out.print("*");
Expand Down Expand Up @@ -320,11 +320,12 @@ This code will print a triangle of stars instead of a rectangle because the inne
@Test
public void testCodeContains()
{
boolean check = checkCodeContains("col=i", "col=i");
boolean check = checkCodeContains("col=row", "col=row");
assertTrue(check);
}
}


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.

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.
Expand Down

0 comments on commit 646fa6f

Please sign in to comment.