C# - Do While Loop
C# - The do...while Loop
Section titled “C# - The do...while Loop”The do...while loop is a post-test loop, meaning it checks its condition after each execution of the loop’s body. This creates a crucial guarantee: the code block inside a do...while loop will always execute at least once, regardless of whether the loop condition is initially true or false.
This makes it the perfect choice for scenarios where an action must be performed before a condition can be evaluated, such as prompting a user for input and then validating that input.
Syntax of the do...while Loop
Section titled “Syntax of the do...while Loop”do{ // statement(s) to be executed; // This block always runs at least once.}while (condition);Flow of Control:
1. The code block inside the `do` statement is executed.2. The boolean `condition` inside the `while()` is evaluated.3. If the condition is `true`, control jumps back to the `do` statement, and the process repeats.4. If the condition is `false`, the loop terminates, and the program continues with the next statement after the loop.Comparison: while vs. do...while
Section titled “Comparison: while vs. do...while”| Feature | while Loop | do...while Loop |
|---|---|---|
| Test Type | Pre-test loop | Post-test loop |
| Execution | Body may execute zero or more times. | Body executes one or more times. |
| Common Use Case | Looping when the condition might already be false. | Looping when the action must happen before the check. |
Practical Use Cases and Examples
Section titled “Practical Use Cases and Examples”The true value of the do...while loop is seen in its practical applications.
1. User Input Validation
Section titled “1. User Input Validation”This is the canonical example. You must first get the input before you can check if it’s valid.
using System;
class Program{ static void Main() { int age; do { Console.Write("Please enter your age (a positive number): "); } while (!int.TryParse(Console.ReadLine(), out age) || age <= 0);
Console.WriteLine($"Thank you. Your age is: {age}"); }}Example interaction:
Please enter your age (a positive number): abcPlease enter your age (a positive number): -5Please enter your age (a positive number): 25Thank you. Your age is: 252. Menu-Driven Programs
Section titled “2. Menu-Driven Programs”Display a menu of options to the user, and keep displaying it until they choose to exit.
using System;
class Program{ static void Main() { string choice; do { Console.WriteLine("\n--- MENU ---"); Console.WriteLine("1. Start New Game"); Console.WriteLine("2. Load Game"); Console.WriteLine("3. Options"); Console.WriteLine("4. Exit"); Console.Write("Enter your choice: "); choice = Console.ReadLine();
// You would typically use a switch statement here to handle the choice
} while (choice != "4");
Console.WriteLine("Exiting program. Goodbye!"); }}This loop will always show the menu once, then continue to show it after each action until the user enters ‘4’.
3. Retry Mechanism
Section titled “3. Retry Mechanism”Attempt a potentially failing operation (like a network connection) and retry a few times before giving up.
using System;using System.Threading.Tasks;
class Program{ // A Random instance should be created once and reused private static readonly Random _random = new Random();
static async Task Main() { bool isConnected = false; int attempt = 0; const int maxAttempts = 3;
do { attempt++; Console.WriteLine($"Attempt {attempt}: Trying to connect to the server...");
// Simulate a network operation that might fail isConnected = (_random.Next(0, 2) == 1);
if (!isConnected && attempt < maxAttempts) { await Task.Delay(1000); // Wait 1 second before retrying }
} while (!isConnected && attempt < maxAttempts);
if (isConnected) { Console.WriteLine("Connection successful!"); } else { Console.WriteLine($"Failed to connect after {maxAttempts} attempts."); } }}Nested do...while Loop
Section titled “Nested do...while Loop”You can nest do...while loops, though it is less common than nesting for loops. It can be useful for scenarios like a simple game that asks if the user wants to play again.
using System;
class Program{ static void Main() { string playAgain; do { Console.WriteLine("\nStarting a new round!"); // Inner loop for the game itself (e.g., number guessing) int numberToGuess = new Random().Next(1, 11); int guess; do { Console.Write("Guess a number between 1 and 10: "); int.TryParse(Console.ReadLine(), out guess); } while (guess != numberToGuess);
Console.WriteLine("You guessed it!");
// Outer loop condition Console.Write("Play again? (yes/no): "); playAgain = Console.ReadLine().ToLower();
} while (playAgain == "yes");
Console.WriteLine("Thanks for playing!"); }}Common Pitfalls
Section titled “Common Pitfalls”- Infinite Loops: Ensure the variable in the
whilecondition is updated within the loop body. If it never changes, your loop may never end. - Forgetting the Semicolon: The
do...whileloop is one of the few control structures in C# that requires a semicolon (;) at the end of thewhile (condition);line. Forgetting it is a common syntax error.