DEV Community

Sabin Sim
Sabin Sim

Posted on

18. C# (Loops)

0. The Real Goal of This Lesson

This is not about syntax.

The goal is to understand how to execute code not just once, but repeatedly under controlled conditions.

Conditionals are:

→ A branching point.

Loops are:

→ A returning structure.

They control different dimensions of execution flow.


1. Why Do We Need Loops?

Current structure:

Show options
Get input
Process
Program ends
Enter fullscreen mode Exit fullscreen mode

But real requirements often look like this:

Show options
Get input
Process
If incorrect → return to start
Enter fullscreen mode Exit fullscreen mode

This means:

The same block of code must run multiple times.

That structure is called a loop.


2. The Core Mental Model of a Loop

Every loop follows this pattern:

Check condition
      ↓
If true → execute block
      ↓
Return to condition check
Enter fullscreen mode Exit fullscreen mode

Execution does not move forward only.

It cycles.


3. The while Loop (Pre-Check Loop)

Structure

while (condition)
{
    // code to repeat
}
Enter fullscreen mode Exit fullscreen mode

The block executes while the condition is true.


Runnable Example

using System;

class Program
{
    static void Main()
    {
        string choice = "";

        while (choice != "E")
        {
            Console.WriteLine("Choose option (A/S/M/E):");
            choice = Console.ReadLine().ToUpper();

            Console.WriteLine($"You selected: {choice}");
        }

        Console.WriteLine("Program ended.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Execution Flow

  1. choice != "E" → true
  2. Execute block
  3. Check condition again
  4. If user enters "E" → condition becomes false → exit loop

4. Structural Meaning of while

while is:

Check first → execute after.

If the condition is false at the beginning:

The block never runs.

Zero executions are possible.

This is called a pre-check loop.


5. The do-while Loop (Post-Check Loop)

Structure

do
{
    // code
}
while (condition);
Enter fullscreen mode Exit fullscreen mode

Key Difference

The block executes at least once.

Because:

Execution happens before the condition check.


Runnable Example

using System;

class Program
{
    static void Main()
    {
        string choice;

        do
        {
            Console.WriteLine("Choose option (A/S/M/E):");
            choice = Console.ReadLine().ToUpper();

            Console.WriteLine($"You selected: {choice}");

        } while (choice != "E");

        Console.WriteLine("Program ended.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Structural Comparison

while do-while
Condition first Execution first
May run 0 times Runs at least 1 time

6. The for Loop (Count-Based Loop)

Use for when:

The number of repetitions is clearly defined.

Structure

for (initialization; condition; increment)
{
    // repeated code
}
Enter fullscreen mode Exit fullscreen mode

Runnable Example

using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine($"Count: {i}");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Flow Breakdown

Initialize i = 1
Check i <= 5
Execute block
Increment i
Repeat
Enter fullscreen mode Exit fullscreen mode

This loop combines:

  • Initialization
  • Condition
  • State change

Into a single structure.


7. The foreach Loop (Collection-Based Loop)

Use foreach when:

You want to process each element in a collection.

Runnable Example

using System;

class Program
{
    static void Main()
    {
        string[] names = { "Alice", "Bob", "Charlie" };

        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The loop:

  • Automatically iterates through the collection
  • Handles indexing internally
  • Focuses on the element itself

8. The Danger of Loops

Infinite Loop

while (true)
{
}
Enter fullscreen mode Exit fullscreen mode

If the condition never becomes false:

The loop never exits.

The program never progresses.

That is why every loop must answer this question:

When does it stop?

Termination logic is not optional.

It is essential.


9. Your Execution Model Must Evolve

Conditionals ask:

“Which path should I take?”

Loops ask:

“Should I return and repeat?”

They operate on different dimensions of flow control.

Understanding this difference is critical.


10. Applying This to a Calculator

Current structure:

Input → Calculate → Exit
Enter fullscreen mode Exit fullscreen mode

With a loop:

while(true)
    Show menu
    Get input
    Process
    If input == "E" → break
Enter fullscreen mode Exit fullscreen mode

Now the program behaves like a real system.

It continues until explicitly told to stop.


Final Summary

A loop is a structure that prevents execution from moving only forward.
It allows code to return and repeat based on a condition.

Top comments (0)