While and Do-While Loops
Loops allow you to repeat code multiple times. This lesson covers while and do-while loops for condition-based iteration.
The while Loop
The while loop repeats code as long as a condition is true:
csharp1int count = 1;23while (count <= 5)4{5 Console.WriteLine($"Count: {count}");6 count++;7}
Output
1Count: 12Count: 23Count: 34Count: 45Count: 5
Syntax
csharp1while (condition)2{3 // Code to repeat4}
- The condition is checked before each iteration
- If the condition is false initially, the loop body never executes
- The loop continues until the condition becomes false
Avoiding Infinite Loops
If the condition never becomes false, you get an infinite loop:
csharp1// DANGER: Infinite loop!2int x = 1;3while (x > 0) // Always true!4{5 Console.WriteLine(x);6 x++; // x keeps growing, never becomes <= 07}89// Correct version:10int x = 1;11while (x <= 10)12{13 Console.WriteLine(x);14 x++; // Eventually x becomes 11, loop stops15}
while Loop Examples
Countdown
csharp1int seconds = 5;23while (seconds > 0)4{5 Console.WriteLine($"{seconds}...");6 seconds--;7 Thread.Sleep(1000); // Wait 1 second8}910Console.WriteLine("Liftoff!");
Sum Numbers
csharp1int sum = 0;2int number = 1;34while (number <= 100)5{6 sum += number;7 number++;8}910Console.WriteLine($"Sum of 1 to 100: {sum}"); // 5050
User Input Validation
csharp1int age = -1;23while (age < 0 || age > 150)4{5 Console.Write("Enter your age (0-150): ");6 string input = Console.ReadLine() ?? "";78 if (!int.TryParse(input, out age) || age < 0 || age > 150)9 {10 Console.WriteLine("Invalid age. Try again.");11 age = -1; // Reset to continue loop12 }13}1415Console.WriteLine($"Your age: {age}");
The do-while Loop
The do-while loop is similar but checks the condition after each iteration:
csharp1int count = 1;23do4{5 Console.WriteLine($"Count: {count}");6 count++;7} while (count <= 5);
Key Difference
The do-while loop always executes at least once:
csharp1// while: may not execute at all2int x = 10;3while (x < 5) // False immediately4{5 Console.WriteLine("This never prints");6}78// do-while: always executes at least once9int y = 10;10do11{12 Console.WriteLine("This prints once"); // Prints!13} while (y < 5); // Then checks condition
do-while Use Cases
Menu System
csharp1string choice;23do4{5 Console.WriteLine("\n=== Menu ===");6 Console.WriteLine("1. Play Game");7 Console.WriteLine("2. Settings");8 Console.WriteLine("3. Exit");9 Console.Write("Choice: ");1011 choice = Console.ReadLine() ?? "";1213 switch (choice)14 {15 case "1":16 Console.WriteLine("Starting game...");17 break;18 case "2":19 Console.WriteLine("Opening settings...");20 break;21 case "3":22 Console.WriteLine("Goodbye!");23 break;24 default:25 Console.WriteLine("Invalid choice!");26 break;27 }28} while (choice != "3");
Input with Retry
csharp1int number;2bool valid;34do5{6 Console.Write("Enter a positive number: ");7 string input = Console.ReadLine() ?? "";8 valid = int.TryParse(input, out number) && number > 0;910 if (!valid)11 {12 Console.WriteLine("Invalid! Try again.");13 }14} while (!valid);1516Console.WriteLine($"You entered: {number}");
Practical Examples
Password Attempts
csharp1const string correctPassword = "secret123";2const int maxAttempts = 3;3int attempts = 0;4bool isLoggedIn = false;56while (attempts < maxAttempts && !isLoggedIn)7{8 Console.Write("Enter password: ");9 string password = Console.ReadLine() ?? "";10 attempts++;1112 if (password == correctPassword)13 {14 isLoggedIn = true;15 Console.WriteLine("Login successful!");16 }17 else18 {19 int remaining = maxAttempts - attempts;20 if (remaining > 0)21 {22 Console.WriteLine($"Wrong password. {remaining} attempts left.");23 }24 }25}2627if (!isLoggedIn)28{29 Console.WriteLine("Account locked. Too many failed attempts.");30}
Reading Until Empty Line
csharp1Console.WriteLine("Enter items (empty line to finish):");2List<string> items = new List<string>();3string input;45while ((input = Console.ReadLine() ?? "") != "")6{7 items.Add(input);8}910Console.WriteLine($"\nYou entered {items.Count} items:");11foreach (string item in items)12{13 Console.WriteLine($" - {item}");14}
Guessing Game Core Loop
csharp1Random random = new Random();2int secret = random.Next(1, 11);3int guess = 0;45Console.WriteLine("Guess a number between 1 and 10!");67while (guess != secret)8{9 Console.Write("Your guess: ");10 if (int.TryParse(Console.ReadLine(), out guess))11 {12 if (guess < secret)13 Console.WriteLine("Too low!");14 else if (guess > secret)15 Console.WriteLine("Too high!");16 }17}1819Console.WriteLine("Correct!");
Summary
In this lesson, you learned:
whileloops check the condition before each iterationdo-whileloops check after, guaranteeing at least one execution- Always ensure the loop condition will eventually become false
- Use while for "zero or more" iterations
- Use do-while for "one or more" iterations
Next, we'll explore for loops for counter-controlled iteration.