3.2.2 - Nested selection and iteration (C#)
Read and write control structures inside other control structures, following which condition controls each statement. Native C# execution is unavailable here; required written answers remain C# and the runnable activity is an optional Python demonstration.
Selection within selection
A nested selection places one decision inside a branch of another decision, so the inner condition is reached only if the outer path allows it.
if (gameWon)
{
Console.WriteLine("Winner");
if (score > highScore)
{
highScore = score;
Console.WriteLine("New record");
}
}
else
{
Console.WriteLine("Try again");
}
If the game is lost, even a high score does not execute the inner test: the outer else runs. If the game is won with score 80 and highScore 100, Winner appears but no record changes. If it is won with score 120, Winner and New record appear, and highScore becomes 120. The inner braces group record-changing instructions; the outer braces group all instructions for a win.
Some nested decisions can be replaced by one combined AND condition, but that could remove required output on intermediate paths. Here Winner must appear for all wins, even when no record is broken. Keep nesting when it expresses the distinct decisions clearly.
Iteration within iteration
A nested loop completes its inner repetitions for each pass of the outer loop before the outer loop advances.
for (int row = 1; row <= 2; row++)
{
for (int column = 1; column <= 3; column++)
{
Console.WriteLine(row + "," + column);
}
}
The pairs appear in this order: 1,1; 1,2; 1,3; 2,1; 2,2; 2,3. The inner counter starts at 1 again for row 2. Two outer passes each perform three inner passes, giving six displays. Putting two loops one after the other would instead perform three plus two passes; it would not pair every row with every column.
Different loop kinds can be nested. Here a fixed three-round match is repeated for each requested match:
bool anotherMatch = true;
while (anotherMatch)
{
for (int round = 1; round <= 3; round++)
{
Console.WriteLine("Round " + round);
}
Console.Write("Another match? yes/no: ");
anotherMatch = Console.ReadLine() == "yes";
}
The for controls the round output; the while controls the whole match and the prompt. The reply is read after all three rounds, and changes the outer condition. In a trace, finish the current inner loop before considering the next outer test.
Predict the optional Python demonstration's six pairs and run it. Change range(1, 4) to range(1, 3) to give two columns per row, then rerun and explain why the count becomes four.
Optional Python demonstration: row and column pairs
{"code":"for row in range(1, 3):\n for column in range(1, 4):\n print(row, column)","instructions":"Predict the six pairs and run. Change the inner range(1, 4) to range(1, 3), predict the new pairs, and run again."}