Skip to Content
Course content

13: While and Do-While Loops

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're standing in front of a vending machine that's acting up. You've got a goal: you want that bag of chips. You press the button, but nothing happens. So, you think to yourself, "As long as the chips haven't dropped, I'm going to keep pressing this button."

That's exactly how a while loop works. You check the condition before you take any action. If the chips are already there (the condition is false), you don't press the button at all. If they aren't there (the condition is true), you press the button, then check again, and repeat.

Now, imagine a different scenario. You're trying a new flavor of soda. You don't know if you like it yet, but you're going to take at least one sip first. After that first sip, you decide: "Do I want to keep drinking this?" This is a do-while loop. You perform the action first, and then you check the condition to see if you should do it again. You are guaranteed to do the action at least once.

Checking the condition first with While

In C#, the while loop is your go-to when you aren't sure if the loop needs to run even once. I often use these when I'm reading data from a file or waiting for a specific user input where the initial state might already be "finished."

int batteryLevel = 15;

while (batteryLevel > 0)
{
    Console.WriteLine($"Phone is running... Battery at {batteryLevel}%");
    batteryLevel -= 5; // We have to change the state, or we're stuck here forever
}

Console.WriteLine("Phone shut down.");

Notice how the condition (batteryLevel > 0) is at the top. If I had set batteryLevel to 0 before the loop started, the code inside the brackets would be completely ignored. The program would just jump straight to "Phone shut down."

Ensuring at least one run with Do-While

The do-while loop is slightly different because the condition is evaluated at the bottom. I personally use these most often for menu systems. You want the user to see the menu at least once before you ask them if they want to quit.

string userChoice;

do
{
    Console.WriteLine("--- Game Menu ---");
    Console.WriteLine("1. Start Game");
    Console.WriteLine("2. Options");
    Console.WriteLine("3. Exit");
    userChoice = Console.ReadLine();
} while (userChoice != "3");

Console.WriteLine("Goodbye!");

In this case, it doesn't matter what userChoice was initially; the menu prints, the user types something, and then the program checks if they typed "3". If they didn't, it loops back to the do block.

The trap of the infinite loop

Here is a piece of advice I give every new dev: always make sure your loop has a "way out." If the condition in a while loop never becomes false, your program will hang, your CPU will spike, and you'll be forced to kill the process in your IDE.

In the battery example above, if I forgot the line batteryLevel -= 5;, the battery would stay at 15 forever, and the loop would never end. When you're debugging, if your console suddenly starts scrolling text at light speed without stopping, you've hit an infinite loop. Don't panic—just hit Ctrl+C or the Stop button and check your loop logic to ensure the variable you're checking is actually being updated inside the body.




📋 Practical Task

Build a Secure PIN Entry Validator

You need to create a program that simulates a secure ATM pin entry. The program should follow these requirements:

  • Define a constant string correctPin = "1234".
  • Use a do-while loop to prompt the user to "Enter your 4-digit PIN:".
  • Inside the loop, capture the user's input.
  • If the input is incorrect, print "Incorrect PIN. Please try again."
  • The loop should continue running as long as the entered PIN does not match the correctPin.
  • Once the correct PIN is entered, exit the loop and print "Access Granted. Welcome to your account!"
Rating
0 0

There are no comments for now.

to be the first to leave a comment.