DEV Community

Sabin Sim
Sabin Sim

Posted on

22. C# (do-while Loop)

Goal

Keep asking the user:

“Enter a word longer than 10 letters.”

Repeat until the condition is satisfied.


1. The do-while Version (The Standard Structure)

Full Runnable Code

using System;

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

        do
        {
            Console.WriteLine("Enter a word longer than 10 letters:");
            word = Console.ReadLine();

        } while (word.Length <= 10);

        Console.WriteLine("Accepted!");
        Console.ReadKey();
    }
}
Enter fullscreen mode Exit fullscreen mode

Thinking Flow

do-while Structure

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

Execution Order

  1. Execute the do block first
  2. Check the condition
  3. If the condition is true → repeat
  4. If the condition is false → exit

That is the core meaning of “runs at least once.”


The Key Condition Here

while (word.Length <= 10);
Enter fullscreen mode Exit fullscreen mode

Meaning:

If the word length is 10 or less, keep repeating.


Why do-while Is Cleaner Here

Because we must collect input at least once.

You cannot evaluate word.Length before the user types something.

That is exactly the scenario where do-while is structurally correct.


2. Implementing the Same Thing With while

using System;

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

        while (word.Length <= 10)  // compile-time error
        {
            Console.WriteLine("Enter a word longer than 10 letters:");
            word = Console.ReadLine();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Why This Fails

Error:

Use of unassigned local variable 'word'

Reason:

  • word has not been assigned yet
  • But you are trying to read word.Length

C# is statically typed and enforces definite assignment.

Uninitialized local variables cannot be used.


Fixing while by Initializing

using System;

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

        while (word.Length <= 10)
        {
            Console.WriteLine("Enter a word longer than 10 letters:");
            word = Console.ReadLine();
        }

        Console.WriteLine("Accepted!");
        Console.ReadKey();
    }
}
Enter fullscreen mode Exit fullscreen mode

This compiles.

But it changes the model:

You are creating an artificial initial state just to make the loop start.

Sometimes that’s fine.

Sometimes it creates hidden bugs.


A Real Pitfall With while

If the requirement changes to:

“Enter a word shorter than 3 letters.”

using System;

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

        while (word.Length >= 3)
        {
            Console.WriteLine("Enter a word shorter than 3 letters:");
            word = Console.ReadLine();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

What happens?

  • Initial word is ""
  • Length is 0
  • 0 >= 3 is false

So:

  • The loop runs zero times
  • The user is never asked
  • No input is collected

This is not a syntax problem.

This is a structural mismatch.


The Core Difference

Structure When condition is checked Minimum executions
while Before execution Can be 0
do-while After execution At least 1

The Mental Model You Must Build

Use while when:

The state already exists, and you repeat while a condition holds.

Example:

int number = 0;

while (number < 10)
{
    number++;
}
Enter fullscreen mode Exit fullscreen mode

Use do-while when:

You must perform the action once before you can evaluate the condition.

Typical scenarios:

  • Login input
  • Re-enter password
  • Menu selection loops
  • Validating user input

Visual Difference

while

Check condition
   ↓
True → execute
False → exit
Enter fullscreen mode Exit fullscreen mode

do-while

Execute once
   ↓
Check condition
True → repeat
False → exit
Enter fullscreen mode Exit fullscreen mode

A Common Real-World Pattern

string choice;

do
{
    Console.WriteLine("Choose A, B or C:");
    choice = Console.ReadLine();

} while (choice != "A" && choice != "B" && choice != "C");
Enter fullscreen mode Exit fullscreen mode

This is the basic menu validation pattern.


Practice Task (Important)

Build this:

Ask the user for a number.
If it is not between 1 and 5, keep asking.

Hint:

while (number < 1 || number > 5)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)