334
The do-while loop in C# is a control flow statement that executes a block of code at least once, and then repeats execution while a specified condition remains true.
It is useful when the loop must run at least one time, regardless of the condition.
This tutorial covers:
- Syntax of the do-while Loop
- How the do-while Loop Works
- Example Usage of do-while Loop
- Using break and continue in a do-while Loop
- Handling User Input with a do-while Loop
- Using a do-while Loop with Arrays and Lists
- Difference Between while and do-while Loops
- Best Practices for Using do-while Loops
1. Syntax of the do-while Loop
The do-while loop executes the loop body first, then checks the condition after each iteration.
Syntax
do { // Code to be executed } while (condition);
- The loop executes at least once because the condition is checked after execution.
2. How the do-while Loop Works
- The loop body executes once, regardless of the condition.
- The condition is checked after execution.
- If true, the loop repeats.
- If false, the loop stops.
Example: Basic do-while Loop
int count = 1; do { Console.WriteLine("Iteration " + count); count++; // Increment count } while (count <= 5);
Output:
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
- count starts at 1 and increments by 1 each time.
- The loop stops when count > 5.
3. Example Usage of do-while Loop
Ensuring Code Runs at Least Once
int number = 10; do { Console.WriteLine("Number is: " + number); } while (number < 5);
Output:
Number is: 10
- Even though number < 5 is false, the loop runs once before stopping.
4. Using break and continue in a do-while Loop
Using break to Exit the Loop
The break statement immediately exits the loop, regardless of the condition.
int num = 1; do { if (num == 5) { Console.WriteLine("Stopping loop at " + num); break; // Exit the loop } Console.WriteLine(num); num++; } while (num <= 10);
Output:
1 2 3 4 Stopping loop at 5
- The loop stops when num == 5.
Using continue to Skip an Iteration
The continue statement skips the current iteration and moves to the next.
int num = 0; do { num++; if (num == 3) { Console.WriteLine("Skipping " + num); continue; // Skips iteration when num == 3 } Console.WriteLine(num); } while (num < 5);
Output:
1 2 Skipping 3 4 5
- The loop skips num = 3 but continues running.
5. Handling User Input with a do-while Loop
A do-while loop is often used to repeatedly ask for user input until a valid response is given.
Example: Asking for a Valid Number
int number; do { Console.Write("Enter a number greater than 0: "); } while (!int.TryParse(Console.ReadLine(), out number) || number <= 0); Console.WriteLine("You entered: " + number);
- TryParse() ensures only valid numbers are accepted.
- The loop repeats until valid input is given.
6. Using a do-while Loop with Arrays and Lists
Iterating Through an Array Using do-while
int[] numbers = { 10, 20, 30, 40, 50 }; int index = 0; do { Console.WriteLine(numbers[index]); index++; // Move to the next index } while (index < numbers.Length);
Output:
10 20 30 40 50
- The loop runs until the end of the array.
Iterating Through a List Using do-while
using System; using System.Collections.Generic; class Program { static void Main() { List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; int index = 0; do { Console.WriteLine(names[index]); index++; } while (index < names.Count); } }
Output:
Alice Bob Charlie
- names.Count provides the list size.
7. Difference Between while and do-while Loops
Feature | while Loop | do-while Loop |
---|---|---|
Condition Check | Before execution | After execution |
Executes At Least Once | No | Yes |
Best Use Case | When condition may be false initially | When execution must happen at least once |
Example: while vs do-while
int number = 10; // while loop (does not execute because condition is false) while (number < 5) { Console.WriteLine("This will not print."); } // do-while loop (executes once before checking condition) do { Console.WriteLine("This will print once."); } while (number < 5);
Output:
This will print once.
- The while loop does not execute because number < 5 is false.
- The do-while loop executes once before checking.
8. Best Practices for Using do-while Loops
Use a do-while Loop When the Code Must Run at Least Once
do { Console.WriteLine("This will always run at least once."); } while (false);
- Ensures execution at least once.
Use break to Exit the Loop If Needed
do { string input = Console.ReadLine(); if (input == "exit") { break; // Exit the loop when "exit" is entered } } while (true);
- break is useful for user-controlled exits.
Use continue to Skip Unwanted Iterations
do { int value = new Random().Next(1, 10); if (value % 2 == 0) continue; // Skip even numbers Console.WriteLine(value); } while (true);
- continue helps skip unnecessary operations.
Use TryParse() for Safe User Input
do { Console.Write("Enter a number: "); } while (!int.TryParse(Console.ReadLine(), out int value));
- This prevents crashes from invalid input.
Conclusion
- The do-while loop executes code at least once before checking the condition.
- Use do-while when an action must run at least once.
- Use break to exit early and continue to skip an iteration.
- Ensure the loop condition eventually becomes false to avoid infinite loops.
- Use do-while loops for user input validation and processing lists/arrays.