C++ Programming Lesson 12: Detailed Explanation of the while Loop and Its Principles

๐Ÿš€ C++ Programming Lesson 12: Detailed Explanation of the while Loop and Its Principles โ€” Flexibly Handling “Unknown Iterations”

C++ Programming Lesson 12: Detailed Explanation of the while Loop and Its Principles

๐Ÿ“š Course Navigation

1ใ€๐Ÿค” Why do we need the while loop? (The “limitations” of for loops and the “advantages” of while loops)2ใ€๐ŸŒŸ Syntax structure of the while loop (A concise and intuitive “condition-driven” model)3ใ€โš™๏ธ Execution principles of the while loop (Step-by-step breakdown of the “condition check โ†’ execution” process)4ใ€๐Ÿงช Practical case: Solving the “unknown iterations” problem (From simple to practical scenarios)5ใ€๐Ÿ†š for loop vs while loop (When to use which?)6ใ€โš ๏ธ Common mistakes with while loops (Avoiding “infinite loops” and “non-execution”)7ใ€๐Ÿ“ข Next lesson preview: Number separation and reversal techniques (Mastering the “decomposition magic” of integers)

1. ๐Ÿค” Why do we need the while loop? โ€” From “known iterations” to “unknown iterations”

In the last lesson, we learned about for loops, which are particularly suitable for scenarios where the number of iterations or range is known in advance, such as “inputting grades 5 times” or “iterating through numbers 1 to 10”. However, in many real-life scenarios, we do not know how many times to loop, only “when to stop”:

  • ๐ŸŽฎ Game scenario: “As long as the player’s health is greater than 0, continue spawning monsters” (not knowing how many times to spawn until health reaches 0);
  • ๐Ÿฅค Shopping scenario: “As long as there is enough money in the wallet to buy a bottle of cola (5 yuan), continue buying” (not knowing how many bottles to buy until the money is insufficient);
  • ๐ŸŽฏ Number guessing game: “As long as the answer is not guessed correctly, continue to let the user guess” (not knowing how many guesses until the correct answer is found).

These scenarios, which have “only a stopping condition and no fixed number of iterations”, are difficult to implement with for loops โ€” this is where the while loop comes into play! It is a “condition-driven” loop that continues to execute as long as the condition is met, making it very flexible.

2. ๐ŸŒŸ Syntax structure of the while loop โ€” A concise “condition + loop body”

The syntax of the while loop is simpler than that of the for loop, consisting of only two core parts: “condition check” and “loop body”, similar to saying “as long as the condition holds, do the following”:

while (condition check expression) { // Loop body: code to repeat when the condition holds // (Note: here you must write code to make the condition gradually false, otherwise it will loop indefinitely) }

We will use the “number guessing game (guess until 5)” as an example, corresponding to the syntax structure:

Syntax part

Function (number guessing game)

Code example

Condition check expression

“As long as the guess is incorrect (user input โ‰  5), continue looping”

guess != 5

Loop body

“Let the user input their guessed number and prompt whether they guessed correctly”

cin >> guess; cout << …;

(Hidden key) Update logic

In the loop body, you need to get new input (guess changes), otherwise the condition will always hold

cin >> guess (updating the value of guess)

Complete code example (number guessing game):

#include <iostream>using namespace std;int main() {    int guess; // Store the user's guessed number    cout << "Number guessing game: Guess a number between 1-10 until you get it right!" << endl;    // while loop: as long as the guess is incorrect (guessโ‰ 5), continue looping    while (guess != 5) {        cout << "Please enter your guessed number:";        cin >> guess; // Update the value of guess each time (key!)        if (guess == 5) {            cout << "Congratulations, you guessed it right!" << endl;        } else {            cout << "Not correct, try again~" << endl;        }    }    return 0;}

Execution scenario:

User inputs 3 โ†’ Prompt “Not correct”; inputs 7 โ†’ Prompt “Not correct”; inputs 5 โ†’ Prompt “You guessed it right”, loop ends.

3. โš™๏ธ Execution principles of the while loop โ€” “Check โ†’ Execute โ†’ Update” three-step loop

The execution of the while loop is like a “little robot checking the condition repeatedly”. Taking the “number guessing game” as an example, we can break it down into three core steps:

Execution steps (corresponding code while (guess != 5) { cin >> guess; … }):

  1. Step 1: Check the condition โ†’ Before each loop, check whether the “condition check expression” holds:
  • First loop: The initial value of guess is uncertain (but definitely โ‰  5), condition holds โ†’ enter the loop body;
  • Subsequent loops: After executing the loop body, return here to recheck (for example, if the user inputs 3, guess=3โ‰ 5, condition holds; if the user inputs 5, guess=5, condition does not hold).
  1. Step 2: Execute the loop body โ†’ Only execute when the condition holds:
  • Get the user’s input for guess (update value);
  • Check if guessed correctly, provide feedback.
  1. Step 3: Repeat steps one and two โ†’ Until the condition does not hold:
  • As long as the condition holds, keep “checking โ†’ executing”;
  • When the condition does not hold (guess=5), immediately exit the while loop and execute the subsequent code.

๐Ÿ“Œ Principle summary:

“Check first, then execute; loop while the condition holds, exit when the condition does not hold” โ€” this is the biggest difference between while loops and for loops (for loops are “initialize first, then check, then execute”).

4. ๐Ÿงช Practical case: Using while loops to solve the “unknown iterations” problem

Case 1: Calculate the cumulative sum “until the sum exceeds 100”

Requirement: Start adding numbers from 1 until the total exceeds 100, finally output the total and the last added number (not knowing how many numbers to add, only knowing the stopping condition “sum > 100”).

#include <iostream>using namespace std;int main() {    int sum = 0; // Store cumulative sum    int num = 1; // Start adding from 1    // while loop: as long as the total <= 100, continue adding    while (sum <= 100) {        sum += num; // Add the current num to sum        if (sum > 100) { // Check if it has exceeded 100            break; // Exit the loop if exceeded to avoid over-adding        }        num++; // If not exceeded, prepare to add the next number (update num)    }    cout << "When the cumulative sum exceeds 100, the total is:" << sum << endl;    cout << "The last added number is:" << num << endl;    return 0;}

Execution result:

When the cumulative sum exceeds 100, the total is: 105

The last added number is: 14 (1+2+…+14=105)

Case 2: “Buy cola as long as there is enough money” scenario

Requirement: The user has an initial amount of money (for example, 20 yuan), cola costs 5 yuan per bottle, buy as long as there is enough money, finally output how many bottles were bought and how much money is left (not knowing how many bottles to buy, stopping condition “money < 5 yuan”).

#include <iostream>using namespace std;int main() {    int money = 20; // Initial amount of money    int count = 0; // Number of cola bottles bought    cout << "Initial amount:" << money << " yuan, cola 5 yuan per bottle" << endl;    // while loop: as long as money >= 5 yuan, continue buying    while (money >= 5) {        money -= 5; // Spend 5 yuan to buy a bottle        count++; // Increase the bottle count by 1        cout << "Bought " << count << " bottles, remaining " << money << " yuan" << endl;    }    cout << "Finally bought " << count << " bottles of cola, remaining " << money << " yuan" << endl;    return 0;}

Execution result:

Initial amount: 20 yuan, cola 5 yuan per bottle

Bought 1 bottle, remaining 15 yuan

Bought 2 bottles, remaining 10 yuan

Bought 3 bottles, remaining 5 yuan

Bought 4 bottles, remaining 0 yuan

Finally bought 4 bottles of cola, remaining 0 yuan

5. ๐Ÿ†š for loop vs while loop โ€” How to choose?

Many beginners ask: “Both for and while can loop, when should each be used?” The core consideration is whether “the number of iterations or range is known”:

Comparison dimension

for loop

while loop

Applicable scenarios

Known number of iterations or range (e.g., loop 5 times, 1 to 10)

Unknown number of iterations, only knowing the stopping condition (e.g., “until guessed correctly”, “until money is sufficient”)

Syntax characteristics

Initialization, check, and update are all in parentheses, compact structure

Only the condition check is in parentheses, initialization and update are outside or in the loop body

Code readability

Suitable for “fixed iterations” scenarios, can see the loop range at a glance

Suitable for “condition-driven” scenarios, highlighting the stopping condition

๐Ÿ“Œ Simple summary:

  • If you can clearly state “how many times to loop” โ†’ use for loop (e.g., “loop 10 times to input grades”);
  • If you can only state “when to stop” โ†’ use while loop (e.g., “stop only when the number is guessed correctly”).

For example, “print 1 to 5”: using a for loop is more convenient (for(int i=1; i<=5; i++));

For example, “print numbers until encountering 0”: using a while loop is more convenient

(while(num != 0) { cout << num; cin >> num; }).

6. โš ๏ธ Common mistakes with while loops

Mistake 1: Forgetting to update the “condition-related variable”, leading to an infinite loop

This is the most common mistake with while loops! For example, in the “number guessing game”, forgetting to write cin >> guess:

// Error: guess remains the initial value (โ‰ 5), condition always holds, loop never stopsint guess;while (guess != 5) {  cout << "Please enter your guessed number:";  // Forgot to write cin >> guess, the value of guess never changes  if (guess == 5) { ... }

โœ… Correct: You must write code to “update the condition variable” in the loop body (e.g., cin >> guess, num++, money-=5) to make the condition gradually false.

Mistake 2: The condition is not met from the start, so the loop does not execute at all

For example, in the case of “cumulative sum exceeding 100”, if the initial sum=101:

// Error: sum initial=101, condition sum <= 100 does not hold, loop does not execute at allint sum = 101;int num = 1;while (sum <= 100) {  sum += num;  num++;}

โœ… Correct: Ensure that the “condition may hold” during initialization (e.g., sum=0), or check if the initial condition is reasonable.

Mistake 3: Using “floating-point numbers” to check conditions, leading to precision issues

For example, in the “money to buy cola” case, using double money to check money >= 5.0:

// Risk: Floating-point numbers have precision errors, for example, money is actually 4.999999999 but displays 5.0, leading to incorrect judgmentdouble money = 5.0;while (money >= 5.0) {  money -= 5.0; // May become -0.000000001, or 4.999999999}

โœ… Correct: In scenarios involving amounts, quantities, etc., try to use integer types (e.g., “cents” instead of “yuan”, int money = 500 cents) to avoid floating-point precision issues.

7. ๐Ÿ“ข Next lesson preview: Number separation and reversal techniques (Mastering the “decomposition magic” of integers)

In this lesson, we learned how to use while loops to solve the “unknown iterations” problem. Next, we will explore the “interesting operations” of integers โ€” such as separating a multi-digit number into single digits (e.g., separating 123 into 1, 2, 3), or reversing a number (e.g., turning 123 into 321), these arenumber separation and reversal techniques!

Many scenarios in life will use these techniques:

  • ๐Ÿ“ฑ Verification code check: “Add each digit of a 6-digit verification code to check if the sum exceeds 20” (requires number separation);
  • ๐Ÿ”ข Palindrome number check: “Check if a number reads the same forwards and backwards (e.g., 121, 1331)” (requires number reversal).

In the next lesson, we will learn:

1ใ€Using “modulus (%10) + integer division (/10)” to achieve number separation (e.g., 123%10 gives 3, 123/10 gives 12, repeat until the number is 0);2ใ€Using while loops to achieve number reversal (e.g., turning 123 into 321, the key is “each time taking the last digit and appending it to the new number”);3ใ€Practical case: Checking if a number is a palindrome, calculating the sum of the digits of a multi-digit number.

Once you master these techniques, you will be able to easily “decompose” and “reassemble” integers, enhancing the program’s ability to handle numbers. Looking forward to exploring positive integers together in the next lesson! ๐Ÿ˜‰

C++ Programming Lesson 12: Detailed Explanation of the while Loop and Its Principles

Leave a Comment