C# - While Loop
C# - The while Loop
Section titled “C# - The while Loop”The while loop is a fundamental control flow statement in C# that repeatedly executes a block of code as long as a given boolean condition evaluates to true. It’s ideal for situations where the number of iterations isn’t known before the loop starts.
Syntax
Section titled “Syntax”The syntax for a while loop is straightforward:
while (condition) { // Code to be executed as long as the condition is true}Here, statement(s) can be a single statement or a block of statements enclosed in curly braces {}. The condition is a boolean expression. The loop continues to iterate as long as the condition is true. When the condition becomes false, the program continues execution at the line immediately following the loop.
Flow Diagram
Section titled “Flow Diagram”The execution flow of a while loop can be visualized as follows:
+--------------------+ | | | Check Condition | | | +---------+----------+ | (Condition is true) (Condition is false) | | +---------v----------+ | | | | | Execute Loop Body | | | | | +--------------------+ | | | +--------------------+-----> [End of Loop]A key characteristic of the while loop is that it is a pre-test loop. The condition is checked before the loop body is executed. This means if the condition is initially false, the loop body will not execute even once.
Example: A Basic Counter
Section titled “Example: A Basic Counter”Let’s look at a simple example that prints numbers from 1 to 5.
using System;
class WhileLoopExample { static void Main() { // 1. Initialization int counter = 1;
// 2. Condition while (counter <= 5) { Console.WriteLine($"Current count: {counter}");
// 3. Update (Increment) // This step is crucial to prevent an infinite loop! counter++; }
Console.WriteLine("Loop finished."); }}When the above code is compiled and executed, it produces the following result:
Current count: 1Current count: 2Current count: 3Current count: 4Current count: 5Loop finished.Common Use Cases and Examples
Section titled “Common Use Cases and Examples”1. User Input Validation
Section titled “1. User Input Validation”A while loop is perfect for repeatedly prompting a user until they provide valid input.
using System;
class InputValidation { static void Main() { int age;
Console.Write("Please enter your age (a positive number): ");
// Loop while the input is not a valid integer OR the parsed number is not positive. while (!int.TryParse(Console.ReadLine(), out age) || age <= 0) { Console.ForegroundColor = ConsoleColor.Red; Console.Write("Invalid input. Please enter a valid positive number for age: "); Console.ResetColor(); }
Console.WriteLine($"Thank you! You entered age: {age}"); }}2. Processing a File Until the End
Section titled “2. Processing a File Until the End”The while loop is ideal for reading a file line-by-line until the end of the file is reached. Modern C# can do this asynchronously.
using System;using System.IO;using System.Threading.Tasks;
class FileProcessor { static async Task Main() { string filePath = "data.txt"; // Ensure a sample file exists for the example await File.WriteAllTextAsync(filePath, "First line.\nSecond line.\nEnd of file.");
Console.WriteLine($"Reading from {filePath}...");
try { using (var reader = new StreamReader(filePath)) { string line; // The loop continues as long as ReadLine() returns a non-null string while ((line = await reader.ReadLineAsync()) != null) { Console.WriteLine(line); } } } catch (FileNotFoundException) { Console.WriteLine($"Error: The file '{filePath}' was not found."); }
File.Delete(filePath); // Clean up the sample file }}3. Game Loop
Section titled “3. Game Loop”In game development, a while loop often forms the core game loop, which runs as long as the game is active.
using System;
class GameLoop { static void Main() { bool isGameRunning = true; int score = 0;
while (isGameRunning) { Console.WriteLine("\n--- Main Menu ---"); Console.WriteLine("1. Play a round"); Console.WriteLine("2. Quit"); Console.Write("Enter your choice: ");
string choice = Console.ReadLine();
if (choice == "1") { score += 10; Console.WriteLine($"You played a round! Your score is now: {score}"); } else if (choice == "2") { isGameRunning = false; // This will cause the loop to terminate } else { Console.WriteLine("Invalid choice, please try again."); } }
Console.WriteLine("Thanks for playing!"); }}Common Mistakes and Debugging
Section titled “Common Mistakes and Debugging”The Infinite Loop: The most common error with while loops is creating an infinite loop. This happens when the loop’s condition never becomes false.
// DANGER: INFINITE LOOPint i = 0;while (i < 5) { Console.WriteLine("This will run forever!"); // The update statement 'i++;' is missing.}Debugging Tip: If your console application hangs, you’ve likely hit an infinite loop. Use your IDE’s debugger to place a breakpoint inside the loop. Step through the code to inspect the variables involved in the condition and see why they are not changing as expected.