Skip to Content
Course content

15: While and Do-While Loops

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

I want to show you a snippet of code I reviewed for a junior dev a while back. They were trying to build a simple calculator that adds numbers together until the user enters 0 to stop. It looked logically sound at a glance, but when they ran it, the program just... finished immediately. It didn't even ask for a single number.

int total = 0;
int number = 0;

while (number != 0) {
    std::cout << "Enter a number (0 to quit): ";
    std::cin >> number;
    total += number;
}

std::cout << "Total sum is: " << total << std::endl;

The Loop That Never Started

The problem here is a classic "chicken and egg" scenario. The developer initialized number to 0. Then, the while loop immediately checks: "Is number not equal to 0?" Since number is exactly 0, the condition is false right out of the gate. The program skips the entire loop body and jumps straight to the final print statement.

You could fix this by initializing number to 1 or some other dummy value, but that's a hack. It's fragile and makes the code confusing for the next person reading it. There's a much cleaner way to handle "do this at least once" logic.

Guaranteeing One Run with do-while

This is exactly why the do-while loop exists. Unlike a standard while loop, which checks the condition before running the block, a do-while loop runs the block first and checks the condition after.

int total = 0;
int number = 0;

do {
    std::cout << "Enter a number (0 to quit): ";
    std::cin >> number;
    total += number;
} while (number != 0);

std::cout << "Total sum is: " << total << std::endl;

Now, the program enters the loop, asks for the number, and adds it to the total before it ever thinks about checking if it should stop. If the user enters 5, the condition 5 != 0 is true, and it loops again. If they enter 0, the condition becomes false, and the loop terminates. It's a much more natural fit for user input.

Choosing the Right Tool for the Job

You might be wondering if you should just use do-while for everything. Not quite. I usually follow a simple rule of thumb: if there is a chance that the loop should never run (for example, processing a list that might be empty), use a while loop.

If you use a do-while on an empty list, you'll likely trigger a crash or a logic error because the code will try to process the first element before realizing the list is empty. A standard while loop protects you from that by checking the state first.

Avoiding the Infinite Loop Trap

One last thing I see people trip over: the infinite loop. This happens when the condition you're checking never becomes false. This usually happens because you forgot to update the variable inside the loop.

int energy = 10;
while (energy > 0) {
    std::cout << "Still running..." << std::endl;
    // If I forget to subtract from energy here, this runs forever.
}

If your program freezes and starts printing the same line a million times a second, don't panic. Just hit Ctrl+C in your terminal to kill the process. When you go back to the code, look for the variable in your while condition and make sure something inside the curly braces is actually changing its value.




📋 Practical Task

Build a Simple Password Retry System

Your task is to create a program that simulates a secure login. The program should have a predefined "secret password" (e.g., "cpp_rocks") stored in a string variable.

Use a do-while loop to repeatedly ask the user to enter the password. If they get it wrong, print "Incorrect password, try again." The loop should continue until the user enters the correct password. Once they succeed, print "Access Granted!"

Requirements:

  • Use std::string for the passwords.
  • The user must be prompted at least once.
  • The loop must terminate immediately upon the correct input.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.