Skip to main content

Section 5.12 Worked Example: Nested Loops

Subgoals for Evaluating a Loop.

  1. Diagram which statements go together.

  2. Define and initialize variables

    1. Determine the start condition.

    2. Determine the update condition.

    3. Determine the termination condition.

    4. Determine body that is repeated.

  3. Trace the loop.

    1. For every iteration of the loop, write down the values.

You can watch this video or read through the content below it.

Problem: Given the following code, what is the output?

int i = 0, j = 0, m = 8, n = 5;
while (i < n)
{
  j = 0;
  while (j < m)
  {
        System.out.print("*");
        j++;
  }
  System.out.println();
  i++;
}

Subsection 5.12.1 SG1: Diagram which statements go together.

Figure 5.12.1.

Subsection 5.12.2 SG2: Define and initialize variables

For now, we begin with the variables that control the outer loop.

Start:

i = 0, n = 5

End:

i >= 5

Subsection 5.12.3 SG3: Trace the loop

Think of an analog clock:

Second hand goes completely around before minute hand moves

Just like inner loop:

Inner loop must finish before outer loop increments once

Figure 5.12.2.

Looking at ONLY the outer loop: <NL> is a new line

Figure 5.12.3.

Now Repeat for inner loop

Subsection 5.12.4 SG1: Diagram which statements go together.

Figure 5.12.4.

Subsection 5.12.5 SG2: Define and initialize variables

Start:

j = 0, m = 8

End:

j >= 8

Subsection 5.12.6 SG3: Trace the loop

Looking at Only the inner loop:

Figure 5.12.5.

Remember, this was just for the first iteration of the outer loop, while i is still value 0.

Figure 5.12.6.

Continuing to the next iteration of the outer loop, i is 1 and j is re-started at value 0:

Figure 5.12.7.

Again, increment i to 2, and j is re-started at 0:

Figure 5.12.8.

Note that outer loop goes 5 times,

Inner loop goes 8 times (for each outer loop)

Figure 5.12.9.

The final output will be 5 lines of 8 asterisks (*).

Practice Pages.

You have attempted of activities on this page.