Metadata
- Date :: 11-04-2025
- Tags :: cpp
Notes
Do-While Loops in C++: Detailed Notes
A do-while loop in C++ is a variation of the regular while loop. The main difference is that in a do-while loop, the block of code is executed at least once, regardless of whether the condition is true or false at the start. After that, it will continue to execute the block of code repeatedly as long as the condition remains true.
Syntax of Do-While Loop:
do {
// Code block to be executed
} while (condition);
- The block of code inside the
dosection is executed at least once. - After executing the block of code, the condition is checked.
- If the condition is true, the loop continues executing the block of code.
- If the condition is false, the loop terminates and the program continues with the rest of the code.
How a Do-While Loop Works:
- Execution Flow:
- The code inside the
doblock runs first, regardless of the condition. - After the execution of the code inside
do, the condition is checked. - If the condition is
true, the loop repeats the code in thedoblock again. - If the condition is
false, the loop terminates.
- The code inside the
Example Explained:
Letβs go through the example given in the video to understand when a do-while loop is useful.
- Scenario: Asking the User for a Positive Number
The goal of the program is to repeatedly ask the user to enter a positive number until they do so.
-
Problem with a while loop: If you use a
whileloop to ask for a positive number, the program might skip the loop entirely if the variable hasnβt been initialized yet or if the condition is false from the start.Example with a
whileloop:int number; while (number < 0) { std::cout << "Enter a positive number: "; std::cin >> number; } std::cout << "The number is " << number;If the number is declared but not initialized (i.e.,
numberstarts with an unknown value), the conditionnumber < 0may fail, and the program may skip asking the user to input the number entirely. This is not the desired behavior because we want the program to prompt the user at least once.
-
Solution with a Do-While Loop:
The
do-whileloop ensures that the code inside the loop executes at least once. This is ideal for situations where you want to prompt the user to enter data but ensure that the prompt is shown at least once.Example using a
do-whileloop:int number; do { std::cout << "Enter a positive number: "; std::cin >> number; } while (number < 0); std::cout << "The number is " << number;- The code inside the
doblock is executed first, prompting the user for a number. - After the user inputs a number, the condition
number < 0is checked. - If the number is negative, the loop repeats, asking the user again to enter a positive number.
- The loop will only exit when the user enters a non-negative number.
This is a perfect use case for a
do-whileloop, ensuring that the user is prompted at least once, and the prompt repeats only if the condition remains true. - The code inside the
Infinite Loops in Do-While:
An interesting point in the video is the demonstration of infinite loops. A loop with a condition that is always true will repeat indefinitely unless there is a break or the program is manually stopped.
For example:
do {
std::cout << "Help! I'm stuck in an infinite loop.";
} while (1 == 1);
In this example, since 1 == 1 is always true, the loop will run indefinitely. You must avoid these situations unless the infinite loop is required for a specific purpose (e.g., a game running continuously until the user opts to quit).
Real-Life Use Case:
A common scenario where a do-while loop is useful is when you want to give the user the option to repeat an action (e.g., asking if they want to play a game again).
Example for playing a game:
char playAgain;
do {
// Play the game
std::cout << "Do you want to play again (y/n)? ";
std::cin >> playAgain;
} while (playAgain == 'y' || playAgain == 'Y');
- The game is played at least once.
- After the game finishes, the program asks the user if they want to play again.
- If the user enters
'y'or'Y', the loop repeats, and the game is played again. - If the user enters anything else, the loop terminates and the program ends.
Advantages of Do-While Loops:
- Guaranteed First Execution: The code in the
doblock is guaranteed to execute at least once, making it useful for cases where the code needs to run first before evaluating the condition. - Simplifies Repetitive Code: It avoids having to duplicate code outside the loop, as you only need to check the condition after the code has been executed.
Key Differences Between While and Do-While Loops:
-
While Loop: The condition is checked before executing the block of code. If the condition is false initially, the code inside the loop will not execute.
Example:
while (condition) { // Code block } -
Do-While Loop: The block of code is executed at least once before checking the condition. Even if the condition is false at the start, the loop will run once.
Example:
do { // Code block } while (condition);
Conclusion:
A do-while loop is an excellent choice when you need to ensure that a block of code executes at least once, especially in cases where user input or repeated actions are involved. It simplifies the logic and avoids the need for duplicate code that would be necessary in a regular while loop. Properly using a do-while loop ensures that the program can handle user input more intuitively and repeat actions when needed.