Back

Activity 1.21: Loops Inside Loops

divider

Activity 1.21

Loops Inside Loops

Key Concepts

The Inner Loop Runs Fully, Every Pass

Nested Loops Multiply

Printing Without a New Line

One Loop

for (int row = 1; row <= 3; row++)
{
Console.WriteLine($"Row {row}");
}

Three passes, three lines. Nothing new.

One Loop

Terminal window
Row 1
Row 2
Row 3

The body of a loop is just a block, and a block can hold anything — including another loop.

A Loop Inside a Loop

for (int row = 1; row <= 3; row++)
{
for (int seat = 1; seat <= 4; seat++)
{
Console.WriteLine($"Row {row} Seat {seat}");
}
}

Before you look: how many lines does this print? Write your number down.

A Loop Inside a Loop

Terminal window
Row 1 Seat 1
Row 1 Seat 2
Row 1 Seat 3
Row 1 Seat 4
Row 2 Seat 1
Row 2 Seat 2
Row 2 Seat 3
Row 2 Seat 4
Row 3 Seat 1
Row 3 Seat 2
Row 3 Seat 3
Row 3 Seat 4

Twelve. Not seven.

The Rule

The inner loop runs all the way through, every single time the outer loop takes one pass.

Row 1 does all four seats before row 2 begins at all.

Look at the output again. The seat number resets to 1 three times. The row number never resets — and that is the whole idea in one observation.

So How Many Times?

for (int a = 1; a <= 3; a++)
{
for (int b = 1; b <= 4; b++)
{
// this line runs 12 times
}
}

Multiply them. 3 outer passes × 4 inner passes = 12.

So How Many Times?

This is why nested loops get slow.

Two loops of 1,000 is a million passes, not two thousand. Three of them nested is a billion.

You meet that properly in Quarter 2 under the name algorithmic efficiency, and it is on the exam. For today it is enough to know the numbers multiply.

You Have Been Using This Since Activity 1.8

Console.Write("Crew size? ");

Every prompt in this course has used Console.Write rather than Console.WriteLine, so the answer could be typed on the same line.

It does not move to a new line. That is the entire difference, and today it does something other than ask a question.

Printing a Row

for (int col = 1; col <= 5; col++)
{
Console.Write("* ");
}
Console.WriteLine();

Five stars on one line, and then one Console.WriteLine() with nothing in it to end the line.

Printing a Row

Terminal window
* * * * *

Put that inside another loop and you have a grid. The inner loop draws one row; the outer loop decides how many rows.

Where the empty Console.WriteLine() sits decides whether you get a grid, a column, or one very long line. You will produce all three today.

Today's Objectives

  • Writing a loop inside another loop
  • Predicting how many times the inner block runs
  • Printing without a new line using Console.Write
  • Using the outer loop's variable inside the inner loop

Key Terms

Nested loop
A loop written inside another loop's body.
Outer loop
The loop that contains the other one.
Inner loop
The loop that runs completely on every pass of the outer one.
Iteration count
How many times a block runs. For nested loops it is the two counts multiplied.

'F' → Fullscreen

divider

Build

Everything today goes in a new program named 1-21-nested-loops.

How to read the code blocks. Each task's code block shows your whole program, from line 1, as it should look when that task is finished.

The green lines marked with a + are the ones you add or change for that task — everything else is already in your file. Do not type the + sign.

Where a block shows only comments, you write that code yourself. The comments stay in your file.


Task 1: Rows and Seats

  • Predict how many lines appear before you run it. Write the number down, then run it and count.
  • Change the inner limit from 4 to 2 and predict again. Run it.
  • Put that back, then change the outer limit from 3 to 2 instead and predict once more. Run it.
  • Write down both predictions and both real answers. They are a graded line on your sheet, and being wrong costs nothing.
  • Put both limits back to 3 and 4 before you continue.
1-21-nested-loops
for (int row = 1; row <= 3; row++)
{
for (int seat = 1; seat <= 4; seat++)
{
Console.WriteLine($"Row {row} Seat {seat}");
}
}

Task 2: An Actual Grid

  • Add a block that prints a rectangle of stars, four rows of six.
  • Look hard at the empty Console.WriteLine(). It is inside the outer loop and below the inner loop, and it is the only thing that ends a row.
  • The inner loop uses Console.Write, which does not move to a new line. Six of those in a row put six stars on one line.
  • Count the stars. There should be twenty-four, and you should be able to say where that number came from without counting.
1-21-nested-loops
for (int row = 1; row <= 3; row++)
{
for (int seat = 1; seat <= 4; seat++)
{
Console.WriteLine($"Row {row} Seat {seat}");
}
}
Console.WriteLine();
for (int row = 1; row <= 4; row++)
{
for (int col = 1; col <= 6; col++)
{
Console.Write("* ");
}
Console.WriteLine();
}

Task 3: Build a Triangle

  • The comments describe a triangle where each row is one star longer than the one above it.
  • The inner loop's limit is the outer loop's variable. That is the whole trick, and it is the first time in this course that the two loops have depended on each other.
  • Convert the input, or the loop header will not compile.
  • Test with 1, then 4, then 7. Then try 0 and say what you expected before you ran it.
1-21-nested-loops
for (int row = 1; row <= 3; row++)
{
for (int seat = 1; seat <= 4; seat++)
{
Console.WriteLine($"Row {row} Seat {seat}");
}
}
Console.WriteLine();
for (int row = 1; row <= 4; row++)
{
for (int col = 1; col <= 6; col++)
{
Console.Write("* ");
}
Console.WriteLine();
}
Console.WriteLine();
// Ask the user for a size and convert it
// Print a triangle that many rows tall:
// row 1 has one star, row 2 has two, and so on
// the inner loop's limit is the outer loop's variable

Task 4: Break It on Purpose

Both changes are to the same line — the empty Console.WriteLine() in your grid. Write down exactly what happens, and put it back before the next one.

  1. Move it inside the inner loop, right after the Console.Write. Run it and count the lines.
  2. Put it back, then delete it entirely. Run it again.

For each one, record how many lines the grid section printed and how many stars were on each. The star total does not change; only its shape does.

Neither version is an error. Both compile, both run, and neither warns you about anything. Say what that one line actually does, now that you have seen the grid, the column, and the single line it sits between.


Challenge (Optional): Upside Down

  • Print a triangle that starts wide and narrows to a single star.
  • There are two ways. Count the outer loop downward, or keep counting upward and subtract. Write whichever occurs to you first.
  • Then work out the other one as well. Both produce identical output, and the second is harder to arrive at than to read.
  • Add a comment saying which reads more clearly and why.
divider

Checkpoint

Your finished program, with 4 as the triangle size.

Example Output
Row 1 Seat 1
Row 1 Seat 2
Row 1 Seat 3
Row 1 Seat 4
Row 2 Seat 1
Row 2 Seat 2
Row 2 Seat 3
Row 2 Seat 4
Row 3 Seat 1
Row 3 Seat 2
Row 3 Seat 3
Row 3 Seat 4
* * * * * *
* * * * * *
* * * * * *
* * * * * *
Size? 4 [Enter]
*
* *
* * *
* * * *
  • Twelve seat lines, and you can say why twelve without counting
  • Four rows of six stars, twenty-four in total
  • The triangle grows by one star a row, and works for 1, 4, and 7
  • You recorded both Task 1 predictions and both real answers
  • Both Task 4 shapes are recorded, with the line and star counts for each
divider

Reflection

Answer the following questions before submitting your work.

  1. Explain why nested loops multiply rather than add, using your rows and seats as the example.
  2. Moving one empty Console.WriteLine() changed your grid into a column, and deleting it made a single long line. Describe what that line does and why its position matters so much.
  3. In the triangle, the inner loop's limit came from the outer loop's variable. Describe something that lets you build which a fixed limit could not.
divider

Submit

Submit four things to the dropbox:

  1. Your 1-21-nested-loops program file.
  2. Both Task 1 predictions with both real answers, and what the triangle did with 0.
  3. Both Task 4 results — line counts and stars per line for each.
  4. Your three reflection answers.

Activity Complete