Skip to main content

C# Do While Loop

Introduction

The do-while loop is a fundamental control flow structure in C# that allows you to execute a block of code repeatedly based on a condition. What makes the do-while loop special is that it always executes the code block at least once before checking the condition. This is different from other loops like the while loop, which checks the condition first before executing any code.

In this tutorial, you'll learn:

  • How the do-while loop works
  • When to use a do-while loop instead of other loops
  • Practical examples and applications
  • Common pitfalls and how to avoid them

Syntax

Here's the basic syntax of a do-while loop:

csharp
do
{
// Code to be executed
} while (condition);

The loop will:

  1. Execute the code block first
  2. Then check the condition
  3. If the condition is true, it will repeat step 1
  4. If the condition is false, it will exit the loop

Basic Example

Let's start with a simple example that counts from 1 to 5:

csharp
using System;

class Program
{
static void Main()
{
int counter = 1;

do
{
Console.WriteLine($"Count: {counter}");
counter++;
} while (counter <= 5);

Console.WriteLine("Loop finished!");
}
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop finished!

How It Works

  1. We initialize a counter variable with value 1
  2. The do block executes, printing the current count and incrementing the counter
  3. After executing the block, the condition counter <= 5 is checked
  4. As long as the condition remains true, the loop continues
  5. When counter becomes 6, the condition becomes false, and the loop ends

Do While vs. While Loop

The key difference between do-while and while is when the condition is evaluated:

csharp
// do-while: executes at least once
int x = 10;
do
{
Console.WriteLine($"do-while: x = {x}");
x--;
} while (x > 0);

// while: may never execute if condition is initially false
int y = 10;
while (y > 0)
{
Console.WriteLine($"while: y = {y}");
y--;
}

When the Condition is Initially False

csharp
int number = 5;

// This will execute once even though the condition is false
do
{
Console.WriteLine($"Do-while executed: {number}");
number++;
} while (number < 5);

// Reset number
number = 5;

// This won't execute at all because the condition is checked first
while (number < 5)
{
Console.WriteLine($"While executed: {number}");
number++;
}

Output:

Do-while executed: 5

Notice that only the do-while block executed, because the while loop checked the condition first and found it false.

Practical Examples

Example 1: User Input Validation

The do-while loop is perfect for scenarios where you want to ensure that users provide valid input:

csharp
using System;

class Program
{
static void Main()
{
int userNumber;

do
{
Console.Write("Please enter a positive number: ");
string input = Console.ReadLine();

if (int.TryParse(input, out userNumber) && userNumber > 0)
{
// Valid input, exit loop
break;
}

Console.WriteLine("Invalid input! Try again.");

} while (true);

Console.WriteLine($"Thank you! You entered: {userNumber}");
}
}

In this example, the loop continues until the user provides a valid positive number.

Example 2: Menu System

A common real-world application is creating a menu system:

csharp
using System;

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

do
{
Console.WriteLine("\n=== Menu ===");
Console.WriteLine("1. View Profile");
Console.WriteLine("2. Edit Settings");
Console.WriteLine("3. Play Game");
Console.WriteLine("4. Exit");
Console.Write("Enter your choice (1-4): ");

if (int.TryParse(Console.ReadLine(), out choice))
{
switch (choice)
{
case 1:
Console.WriteLine("Loading profile...");
break;
case 2:
Console.WriteLine("Opening settings...");
break;
case 3:
Console.WriteLine("Starting game...");
break;
case 4:
Console.WriteLine("Goodbye!");
break;
default:
Console.WriteLine("Invalid option! Please select 1-4.");
break;
}
}
else
{
Console.WriteLine("Please enter a valid number!");
choice = 0; // Reset choice
}

} while (choice != 4); // Continue loop until Exit option is selected
}
}

This menu system keeps showing options until the user selects the exit option.

Example 3: Processing File Data

The do-while loop can be useful when reading data until you reach the end of a file:

csharp
using System;
using System.IO;

class Program
{
static void Main()
{
string line;
int lineCount = 0;

try
{
StreamReader file = new StreamReader("sample.txt");

do
{
line = file.ReadLine();

if (line != null)
{
lineCount++;
Console.WriteLine($"Line {lineCount}: {line}");
}

} while (line != null);

file.Close();
Console.WriteLine($"\nTotal lines: {lineCount}");
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found!");
}
}
}

Common Pitfalls and Best Practices

1. Infinite Loops

Be careful not to create infinite loops. Always ensure that your condition will eventually become false:

csharp
// Potential infinite loop if you forget to update counter
do
{
Console.WriteLine("This might never end!");
// Missing: counter++;
} while (counter < 10);

2. Condition Variables

Make sure that variables used in your condition are properly updated within the loop:

csharp
int x = 5;
do
{
Console.WriteLine($"x = {x}");
x--; // Important: without this, the loop would be infinite
} while (x > 0);

3. Scope of Variables

Variables declared within the do block are not accessible in the while condition:

csharp
do
{
int count = 5; // Local to this block
Console.WriteLine(count);
} while (count > 0); // Error! 'count' doesn't exist in this scope

The correct approach is to define the variables before the loop:

csharp
int count = 5;
do
{
Console.WriteLine(count);
count--;
} while (count > 0);

When to Use Do While vs. Other Loops

Use a do-while loop when:

  • You need to execute a block of code at least once before checking a condition
  • Validating user input (as shown in examples)
  • Creating menu systems that should display at least once
  • Processing data where you need to read before checking for end conditions

Use a regular while loop when:

  • You might want to skip execution entirely based on an initial condition
  • The number of iterations is unknown but depends on a condition

Use a for loop when:

  • The number of iterations is known or can be calculated
  • You need more structured loop components (initialization, condition, iteration)

Summary

The do-while loop is a powerful construct in C# that guarantees at least one execution of a code block before checking a condition. This makes it particularly useful for:

  • User input validation
  • Menu-based interfaces
  • Scenarios where code must run at least once

Remember these key points:

  • The loop body always executes at least once
  • The condition is checked after the loop body executes
  • Be careful to avoid infinite loops by ensuring your condition will eventually become false

By understanding and correctly implementing do-while loops, you'll have another valuable tool in your C# programming toolkit.

Exercises

To solidify your knowledge, try these exercises:

  1. Create a guessing game where the user tries to guess a random number between 1 and 100, giving them hints if their guess is too high or too low.

  2. Write a program that calculates the average of a series of numbers entered by the user. Use a do-while loop to keep asking for numbers until the user enters a negative number.

  3. Implement a simple calculator program using a do-while loop that keeps performing operations until the user chooses to exit.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)