CodeBlanks Logo Icon CodeBlanks

Summary - Loops

C# course · Beginner · Lesson 47/116

Combine for, while and foreach to write a multiplication table.

Summary - Loops

In this group you learned for, while, do-while, foreach and break/continue. Now you will combine them to write a multiplication table.

Across two exercises you will first produce a 1-5 multiplication table with nested for, then sum a number array with foreach. Nested loops and accumulation meet here.

Exercise Write a multiplication table

Write two nested for loops: outer i from 1 to 3, inner j from 1 to 3. Each step prints i * j with Console.WriteLine. The output should be 1, 2, 3, 2, 4, 6, 3, 6, 9.

Show example solution
outer i (1-3), inner j (1-3). In the body write Console.WriteLine(i * j);
Example solution:
using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 3; i++)
        {
            for (int j = 1; j <= 3; j++)
            {
                Console.WriteLine(i * j);
            }
        }
    }
}

Exercise Sum an array with foreach

Declare a nums array: { 4, 8, 15 }. Set a sum variable to 0. Use foreach to add each element to sum (sum += n). After the loop, print sum with Console.WriteLine.

Show example solution
Write int[] nums = { 4, 8, 15 }; int sum = 0; foreach (var n in nums) { sum += n; } Console.WriteLine(sum);
Example solution:
using System;

class Program
{
    static void Main()
    {
        int[] nums = { 4, 8, 15 };
        int sum = 0;
        foreach (var n in nums)
        {
            sum += n;
        }
        Console.WriteLine(sum);
    }
}

The loops side by side

You now know five loop tools: for, while, do-while, foreach and break/continue. Which one to pick depends on the context.

When the count is known, for; condition first, while; at least once, do-while; walking a collection, foreach; early exit or skip, break/continue. Nested loops shine in multiplication tables and matrices.

Test yourself

  1. Which loop runs the body at least once?

    // which one?
    • while
    • do-while
    • for
    • foreach
    Show answer

    do-while — Correct. do-while checks the condition at the end; the body runs at least once.

  2. Complete the nested for header

    for (int i = 1; i <= 5; i++)
    {
        ____ (int j = 1; j <= 5; j++)
        {
            Console.WriteLine(i * j);
        }
    }
    Show answer
    for (int i = 1; i <= 5; i++)
    {
        for (int j = 1; j <= 5; j++)
        {
            Console.WriteLine(i * j);
        }
    }

All lessons in Beginner