BuildQuill
C# learning path
7 of 25
Lesson 7 of 25
Lesson 7Beginner18 min

C# Loops

Repeat work without copying statements, trace loop state safely, and choose for, while, do-while, or foreach from the problem.

Before this lesson

  • Conditions
  • Variables and assignment
  • Comparison operators

Trace initialization, condition, body, and update

Choose a loop from the source of repetition

Prevent off-by-one and infinite-loop mistakes

The short answer

A loop repeats a block. Use for when a counter or index controls repetition, while when an unknown number of repetitions depends on a condition, do-while when the body must run once, and foreach when visiting every item in a sequence.

01

Repetition should have one source of truth

Copying the same statement four times works only until the count changes or a correction must be made in every copy. A loop keeps the repeated action in one place and makes the repetition rule explicit. Each pass through the body is called an iteration.

Every terminating loop needs progress toward a stopping condition. The progress may be a counter increasing, input changing, or work being removed from a queue. When neither the condition nor relevant state can change, the loop may never end.

02

Trace a for loop in four parts

A for header contains initialization, condition, and update. Initialization runs once. The condition is checked before each iteration. If true, the body runs, then the update runs, and the condition is checked again. When false, execution continues after the loop.

In the example, day starts at 1, continues while day <= 3, and increases by one. The sequence is 1, 2, 3. Using day < 3 would stop before 3; using day <= 4 would add one extra iteration. These boundary mistakes are called off-by-one errors.

C#
using System;

class Program
{
  static void Main()
  {
      for (int day = 1; day <= 3; day++)
      {
          Console.WriteLine($"Day {day}");
      }
  }
}

Expected output

Day 1
Day 2
Day 3
03

Use while when the number of attempts is unknown

A while loop checks a condition before every iteration. It suits retrying until valid input arrives, processing until no work remains, or simulating until a state is reached. The body may run zero times when the condition starts false.

A do-while checks after the body, so it runs at least once. That can suit a menu that must display before asking whether to continue. It is less common, and while is often easier to reason about because the gate appears first.

C#
int battery = 3;

while (battery > 0)
{
  Console.WriteLine($"Working; charge: {battery}");
  battery--;
}

Console.WriteLine("Battery empty");

Expected output

Working; charge: 3
Working; charge: 2
Working; charge: 1
Battery empty
04

Use foreach to visit values rather than manage positions

When the goal is to process every value in a collection, foreach says that directly. It asks the sequence for each item and assigns the current item to a loop variable. You do not need to manage an index or length, which removes common boundary errors.

A for loop is still useful when position matters, when you need to replace items by index, or when stepping by something other than one. Choose based on what the algorithm needs, not on which syntax is shortest.

LoopBest signalWatch for
forKnown count or index neededBoundary and update errors
whileRepeat until state changesState that never changes
do-whileBody must run onceAccidental extra first iteration
foreachVisit every sequence itemModifying the collection while iterating
C#
string[] cities = { "Karachi", "Riyadh", "Istanbul" };

foreach (string city in cities)
{
  Console.WriteLine(city);
}
05

Break and continue change the local flow

break exits the nearest loop immediately. continue skips the rest of the current iteration and starts the next one. They are useful when they express an early decision clearly, such as stopping after a match or ignoring invalid records.

Too many jumps can make a loop hard to trace. First consider whether a better loop condition or a small method would state the rule more directly. Avoid goto in ordinary beginner code; structured loops and methods provide clearer control flow.

Good habits

  • Write the expected first and last values beside a new counter loop.
  • During debugging, print the counter and the state that should move toward termination.
  • Do not modify a List by adding or removing items inside its foreach loop.

Quick knowledge check

Answer before you reveal.

01How many times does for (int i = 0; i < 4; i++) run?

Four times, with i equal to 0, 1, 2, and 3.

02What must you inspect first in an infinite while loop?

Check whether any state used by the condition can change toward making that condition false.

Practice challenge

Now build it without copying.

Print a repayment schedule for a 100 balance reduced by 15 each month. Show the month and remaining balance, never print a negative balance, and stop when it reaches zero.

You are done when

  • The loop terminates
  • The balance changes on every iteration
  • The final displayed balance is zero rather than negative

Stretch: Count how many months repayment required and print the count after the loop.

Open challenge in playground

Lesson checkpoint

One small step locks it in

Mark this lesson complete, then keep the momentum going.

Complete and continue

Clear up the details

Frequently asked questions

Is foreach slower than for?

Performance depends on the collection and context, and the difference is usually irrelevant in beginner programs. Choose the loop that communicates the algorithm; measure only when performance matters.

Can I put a loop inside another loop?

Yes. Nested loops suit grids and combinations, but work multiplies: a 100-by-100 pair produces 10,000 inner iterations. Name both counters clearly.

When should a loop be replaced by LINQ?

LINQ is useful for describing transformations and queries. Learn explicit loops first so you can reason about work, state, and edge cases underneath the higher-level syntax.