10 minlesson

While and Do-While Loops

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:

csharp
1int count = 1;
2
3while (count <= 5)
4{
5 Console.WriteLine($"Count: {count}");
6 count++;
7}

Output

1Count: 1
2Count: 2
3Count: 3
4Count: 4
5Count: 5

Syntax

csharp
1while (condition)
2{
3 // Code to repeat
4}
  • 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:

csharp
1// DANGER: Infinite loop!
2int x = 1;
3while (x > 0) // Always true!
4{
5 Console.WriteLine(x);
6 x++; // x keeps growing, never becomes <= 0
7}
8
9// Correct version:
10int x = 1;
11while (x <= 10)
12{
13 Console.WriteLine(x);
14 x++; // Eventually x becomes 11, loop stops
15}

while Loop Examples

Countdown

csharp
1int seconds = 5;
2
3while (seconds > 0)
4{
5 Console.WriteLine($"{seconds}...");
6 seconds--;
7 Thread.Sleep(1000); // Wait 1 second
8}
9
10Console.WriteLine("Liftoff!");

Sum Numbers

csharp
1int sum = 0;
2int number = 1;
3
4while (number <= 100)
5{
6 sum += number;
7 number++;
8}
9
10Console.WriteLine($"Sum of 1 to 100: {sum}"); // 5050

User Input Validation

csharp
1int age = -1;
2
3while (age < 0 || age > 150)
4{
5 Console.Write("Enter your age (0-150): ");
6 string input = Console.ReadLine() ?? "";
7
8 if (!int.TryParse(input, out age) || age < 0 || age > 150)
9 {
10 Console.WriteLine("Invalid age. Try again.");
11 age = -1; // Reset to continue loop
12 }
13}
14
15Console.WriteLine($"Your age: {age}");

The do-while Loop

The do-while loop is similar but checks the condition after each iteration:

csharp
1int count = 1;
2
3do
4{
5 Console.WriteLine($"Count: {count}");
6 count++;
7} while (count <= 5);

Key Difference

The do-while loop always executes at least once:

csharp
1// while: may not execute at all
2int x = 10;
3while (x < 5) // False immediately
4{
5 Console.WriteLine("This never prints");
6}
7
8// do-while: always executes at least once
9int y = 10;
10do
11{
12 Console.WriteLine("This prints once"); // Prints!
13} while (y < 5); // Then checks condition

do-while Use Cases

Menu System

csharp
1string choice;
2
3do
4{
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: ");
10
11 choice = Console.ReadLine() ?? "";
12
13 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

csharp
1int number;
2bool valid;
3
4do
5{
6 Console.Write("Enter a positive number: ");
7 string input = Console.ReadLine() ?? "";
8 valid = int.TryParse(input, out number) && number > 0;
9
10 if (!valid)
11 {
12 Console.WriteLine("Invalid! Try again.");
13 }
14} while (!valid);
15
16Console.WriteLine($"You entered: {number}");

Practical Examples

Password Attempts

csharp
1const string correctPassword = "secret123";
2const int maxAttempts = 3;
3int attempts = 0;
4bool isLoggedIn = false;
5
6while (attempts < maxAttempts && !isLoggedIn)
7{
8 Console.Write("Enter password: ");
9 string password = Console.ReadLine() ?? "";
10 attempts++;
11
12 if (password == correctPassword)
13 {
14 isLoggedIn = true;
15 Console.WriteLine("Login successful!");
16 }
17 else
18 {
19 int remaining = maxAttempts - attempts;
20 if (remaining > 0)
21 {
22 Console.WriteLine($"Wrong password. {remaining} attempts left.");
23 }
24 }
25}
26
27if (!isLoggedIn)
28{
29 Console.WriteLine("Account locked. Too many failed attempts.");
30}

Reading Until Empty Line

csharp
1Console.WriteLine("Enter items (empty line to finish):");
2List<string> items = new List<string>();
3string input;
4
5while ((input = Console.ReadLine() ?? "") != "")
6{
7 items.Add(input);
8}
9
10Console.WriteLine($"\nYou entered {items.Count} items:");
11foreach (string item in items)
12{
13 Console.WriteLine($" - {item}");
14}

Guessing Game Core Loop

csharp
1Random random = new Random();
2int secret = random.Next(1, 11);
3int guess = 0;
4
5Console.WriteLine("Guess a number between 1 and 10!");
6
7while (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}
18
19Console.WriteLine("Correct!");

Summary

In this lesson, you learned:

  • while loops check the condition before each iteration
  • do-while loops 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.