Skip to main content
ANVISoftware Solutions
Lesson 9 of 15Beginner15 min

Loops

By the end of this lesson

Repeat work without duplicating code, and choose the loop that fits the situation.

A loop repeats a block of code. Without loops, processing a hundred orders would mean writing the same lines a hundred times — and rewriting all of them when the logic changed.

foreach — for every item in a collection

C#
string[] cities = { "Pune", "Mumbai", "Bengaluru" };

foreach (string city in cities)
{
    Console.WriteLine($"Office: {city}");
}
  • The loop runs once per item. Each time, city holds the current one.
  • You never manage a counter, so you cannot run past the end of the collection. This is the loop to reach for by default.

for — when you need the index or a specific count

C#
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"Line {i}");
}
  • Three parts, separated by semicolons: start at 1; keep going while i is at most 5; add 1 each time.
  • i++ is shorthand for i = i + 1.
  • Use this when the number itself matters, or when you need to walk a collection by position.

while — when you do not know how many times

C#
decimal balance = 100m;
int months = 0;

while (balance > 0)
{
    balance -= 30m;
    months++;
}

Console.WriteLine($"Exhausted after {months} months.");
  • The condition is checked before each pass. When it becomes false, the loop ends.
  • Something inside the loop must eventually make the condition false, or it never stops.

Choosing between them:

 Use foreach / forUse while
You know the countYes — a collection, or a fixed number of passesNo — it depends on what happens inside
Typical exampleProcess every order in a listKeep reading input until the user types quit
Risk of never endingVery lowReal — you must make progress toward the exit

In a real application

An invoice run loops over every unpaid invoice, decides for each whether a reminder is due, and sends one if so. That is a foreach containing an if — the two ideas from this module combined, which is most of what ordinary business logic consists of.

Summary

  • Loops repeat work so you write the logic once
  • foreach for every item, for when the index or count matters, while when the end depends on what happens inside
  • A while loop must make progress toward its exit condition or it never stops
  • Variables that need to survive between passes must be declared outside the loop

Practice

Attempt each one before opening the solution. Getting it wrong first is how the idea sticks.

Try it yourself

Try it yourself

Given an array of order totals, print each one and then print the sum of all of them.

The sum variable must be declared before the loop. Consider why.

Show solution

The running total has to survive between passes, so it must be declared outside. A variable declared inside the loop would be created fresh each time and lost at the end of each pass.

C#
decimal[] orderTotals = { 24.99m, 150.00m, 8.50m, 62.25m };
decimal sum = 0m;

foreach (decimal total in orderTotals)
{
    Console.WriteLine($"Order: {total}");
    sum += total;
}

Console.WriteLine($"Total: {sum}");

Challenge

Challenge

Print the numbers 1 to 30, but for multiples of 3 print "three" instead of the number, and for multiples of 5 print "five". For multiples of both, print "both".

Show solution

The key is testing the combined case first. If you check for multiples of 3 before checking for both, 15 will match the first test and never reach the combined branch — the ordering issue from the conditions lesson, appearing in practice.

C#
for (int i = 1; i <= 30; i++)
{
    if (i % 3 == 0 && i % 5 == 0)
    {
        Console.WriteLine("both");
    }
    else if (i % 3 == 0)
    {
        Console.WriteLine("three");
    }
    else if (i % 5 == 0)
    {
        Console.WriteLine("five");
    }
    else
    {
        Console.WriteLine(i);
    }
}

Knowledge check

Nothing is recorded and there is no score. The explanation appears either way.

Which loop is the safest default for processing every item in a list?

Saved in this browser only.