C++
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented C++
-
Section 4: Memory Management
-
Section 5: Templates and Generic Programming
-
Section 6: The Standard Template Library
-
Section 7: Modern C++ Features
-
Section 8: Error Handling
-
Section 9: Multithreading
-
Section 10: Operator Overloading and Type Conversion
-
Section 11: Advanced Topics
-
Section 12: Tooling and Build Systems
-
Section 13: Design Patterns in C++
-
Section 14: Interfacing with C and Systems Programming
-
Section 15: Networking and IPC Basics
-
Section 16: Graphics and Game Programming Basics
-
Section 17: The Boost Libraries
-
Section 18: Data Structures and Algorithms in C++
-
Section 19: Practical Projects
-
Section 20: More Concurrency Patterns
-
Section 21: More OOP and Design Practice
-
Section 22: File I/O and Streams
-
Section 23: More Standard Library
-
Section 24: Practice Exercises
-
Section 25: Interview and Algorithm Practice
-
Section 26: Compiler and Language Internals
-
Section 27: GUI and Application Frameworks Overview
-
Section 28: Testing and Quality Practices
-
Section 29: Numerics Library
-
Section 30: Concepts Library (C++20)
-
Section 31: Ranges Library (C++20) In Depth
-
Section 32: More Utility Library
15: While and Do-While Loops
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::stringfor the passwords. - The user must be prompted at least once.
- The loop must terminate immediately upon the correct input.
There are no comments for now.