Today, we will explore a very basic yet extremely powerful “magic spell” in C language – the <span>while</span> statement. It allows your program to repeatedly execute certain tasks, greatly improving efficiency, making it a “time machine” in the programming world!
1. What is the <span>while</span> statement?
Imagine you are playing a game where you need to repeatedly attack the same enemy until its health reaches zero. Or, you are writing a program that needs to repeatedly read user input until the user types “quit”. In this case, you need a structure that allows the program to “loop” through a specific block of code, and the <span>while</span> statement is one of the tools in C language to achieve this “looping”.
<span>while</span> statement in C language is an entry-controlled loop. This means that before each iteration of the loop, it checks a condition expression. Only when this condition expression is true (non-zero) will the code inside the loop body be executed. If the condition is false (zero), the loop will terminate immediately.
Its basic syntax structure is as follows:
while (condition expression) {
// Loop body: the code here will be executed repeatedly when the condition is true
}
<span>while</span>: A keyword indicating that this is a<span>while</span>loop.<span>condition expression</span>: This is an expression that can produce a boolean value (true or false). It can be any valid C language expression, such as relational expressions (<span>a > b</span>), logical expressions (<span>a && b</span>), or even a variable (non-zero is true, zero is false).<span>{}</span>: Curly braces indicate the loop body. When the condition expression is true, all statements within the curly braces will be executed. If the loop body contains only one statement, the curly braces can be omitted, but for code readability and to avoid potential errors, it is strongly recommended to always use curly braces.
2. When to use the <span>while</span> statement?
-
When to use it?
- When you are unsure how many times the loop needs to execute: This is the most common application scenario for the
<span>while</span>loop. For example, you need the user to repeatedly input a number until a specific value (like -1) is entered to stop. Or you need to read a file until the end of the file. In these cases, you do not know in advance how many times the loop will execute. - When you need to repeat tasks based on specific conditions: As long as a certain condition is met, keep executing. For example, calculating the factorial of a number as long as the number is greater than 1.
- When you need to implement “waiting” or “listening” logic: For example, in an embedded system, waiting for a certain sensor signal to reach a specific value.
-
Why use it?
- Improve code reusability: Avoid rewriting the same code, making the program more concise and easier to maintain.
- Implement complex logic: Many algorithms and programs require loop structures to handle repetitive tasks.
- Handle iterations of unknown counts: The
<span>while</span>loop performs excellently when the number of iterations is unknown. -
Relation and distinction with related knowledge points:
- Difference:
<span>do-while</span>loop is an exit-controlled loop. It executes the loop body once before checking the condition. This means that the<span>do-while</span>loop will execute at least once, while the<span>while</span>loop may not execute at all if the condition is not satisfied at the beginning. - Relation: Both loops are used to repeatedly execute code but are suitable for different scenarios.
- Example:
<span>while</span>:<span>while (input != 'q') { ... }</span>(If the first input is ‘q’, the loop body will not execute)<span>do-while</span>:<span>do { ... } while (input != 'q');</span>(The user will input at least once regardless)- Difference:
<span>for</span>loop is usually used when the number of iterations is known or when the loop variable has a clear initialization, condition, and stepping pattern. Its structure is more compact, placing the initialization of the loop control variable, loop condition, and update all in one line. - Relation: Any
<span>for</span>loop can be rewritten as a<span>while</span>loop and vice versa. However, which loop to choose depends on your specific needs and code readability. If the number of iterations is known or there is a clear counter, the<span>for</span>loop is usually better; if the loop condition is more based on a certain state rather than counting, the<span>while</span>loop is more suitable. - Example:
<span>for</span>loop:<span>for (int i = 0; i < 10; i++) { ... }</span>(Print 10 times)<span>while</span>loop:<span>int i = 0; while (i < 10) { ...; i++; }</span>(Also prints 10 times)-
<span>for</span>loop: -
<span>do-while</span>loop:
3. How to use the <span>while</span> statement?
Let’s experience the charm of the <span>while</span> loop through a few practical programming scenarios!
Scenario 1: Simple Counter
#include <stdio.h>
int main() {
int count = 1; // Initialize counter
printf("Starting countdown!\n");
// Loop executes while count is less than or equal to 5
while (count <= 5) {
printf("Current number: %d\n", count);
count++; // Increment counter after each loop to avoid infinite loop
}
printf("Countdown finished!\n");
return 0;
}
Output:
Starting countdown!
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5
Countdown finished!
Analysis: Initially, <span>count</span> is 1, satisfying <span>count <= 5</span>, executing <span>printf</span> and <span>count++</span>. <span>count</span> becomes 2, continues to satisfy the condition until <span>count</span> becomes 6, at which point the condition <span>count <= 5</span> is not satisfied, and the loop terminates.
Scenario 2: User Input Validation (until a valid value is entered)
#include <stdio.h>
int main() {
int age;
printf("Please enter your age (between 1-120):\n");
// Loop continues as long as age is not in the valid range
while (scanf("%d", &age) != 1 || age < 1 || age > 120) {
// scanf("%d", &age) != 1 indicates input is not an integer
// age < 1 || age > 120 indicates age is not in the valid range
printf("Invalid input, please re-enter your age (between 1-120):\n");
// Clear input buffer to avoid infinite loop reading erroneous input
while (getchar() != '\n' && getchar() != EOF);
}
printf("Your age is: %d years. Input valid!\n", age);
return 0;
}
Analysis: This example demonstrates the powerful role of the <span>while</span> loop in input validation. As long as the value entered by the user does not meet the conditions, it will keep prompting for re-entry until a valid value is entered. The return value of <span>scanf</span> and clearing the buffer are common techniques when handling user input.
Scenario 3: Guess the Number Game
#include <stdio.h>
#include <stdlib.h> // For rand() and srand()
#include <time.h> // For time()
int main() {
srand(time(NULL)); // Use current time as random seed
int target_number = rand() % 100 + 1; // Generate a random number between 1 and 100
int guess;
int attempts = 0;
printf("Welcome to the Guess the Number game!\n");
printf("I have thought of a number between 1 and 100, can you guess it?\n");
// Loop continues as long as the guessed number is not equal to the target number
while (guess != target_number) {
printf("Please enter your guess:");
scanf("%d", &guess);
attempts++; // Increment attempt count
if (guess > target_number) {
printf("Too high!\n");
} else if (guess < target_number) {
printf("Too low!\n");
} else {
printf("Congratulations, you guessed it right!\n");
printf("You guessed a total of %d times.\n", attempts);
}
}
return 0;
}
Analysis: This is a classic guessing game. The <span>while</span> loop here controls the progress of the game, continuing as long as the player has not guessed correctly. This perfectly illustrates the application of the <span>while</span> loop in scenarios with “unknown execution counts”.
Through these examples, I believe you have gained a deeper understanding of the <span>while</span> statement’s “what it is”, “when to use it”, and “how to use it”. Remember, loops are a very important concept in programming, and mastering them will greatly enhance your programming skills!
📝 Accompanying Exercises
1. Multiple Choice Question
Which of the following options is a correct description of the <span>while</span> loop?A. <span>while</span> loop executes the loop body at least once.B. <span>while</span> loop checks the condition expression before executing the loop body.C. <span>while</span> loop is usually used in scenarios with known loop counts.D. <span>while</span> loop’s condition expression must be a boolean constant.
2. True or False Question
<span>while</span> loop’s condition expression, if false (0) at the beginning, will not execute the code inside the loop body.A. TrueB. False
3. Fill in the Blanks
Use the <span>while</span> loop to print all integers from 10 to 1 (inclusive) and change lines after each number.
#include <stdio.h>
int main() {
int num = 10;
while (num ____ 1) {
printf("%d\n", num);
num____;
}
return 0;
}
4. Programming Question: Calculate Fibonacci Sequence
Write a C program that uses the <span>while</span> loop to calculate and print the first N terms of the Fibonacci sequence. The Fibonacci sequence is defined as: F(0)=0, F(1)=1, F(n) = F(n-1) + F(n-2) (n ≥ 2). The program should prompt the user to input N.
Example Input:5
Example Output:The first 5 terms of the Fibonacci sequence are: 0 1 1 2 3
5. Programming Question: Reverse a Number
Write a C program that uses the <span>while</span> loop to reverse the digits of a positive integer. For example, input 12345, output 54321.
Example Input:12345
Example Output:The reversed number is: 54321
💡 Exercise Explanations
1. Multiple Choice Question
Which of the following options is a correct description of the <span>while</span> loop? A. <span>while</span> loop executes the loop body at least once. B. <span>while</span> loop checks the condition expression before executing the loop body. C. <span>while</span> loop is usually used in scenarios with known loop counts. D. <span>while</span> loop’s condition expression must be a boolean constant.
Answer: B
Explanation:
- Option A is incorrect:
<span>while</span>loop is an entry-controlled loop; if the condition expression is false at the beginning, the loop body will not execute at all. The<span>do-while</span>loop executes at least once. - Option B is correct: This is a defining feature of the
<span>while</span>loop; it checks the condition first, and only enters the loop body if the condition is true. - Option C is incorrect:
<span>while</span>loop is more commonly used in scenarios where the number of iterations is uncertain, while the<span>for</span>loop is usually used in scenarios with known loop counts. - Option D is incorrect:
<span>while</span>loop’s condition expression can be any expression that produces a non-zero (true) or zero (false) value, such as relational expressions, logical expressions, or variables, not limited to boolean constants.
2. True or False Question
<span>while</span> loop’s condition expression, if false (0) at the beginning, will not execute the code inside the loop body. A. True B. False
Answer: A
Explanation: This is the core feature of the <span>while</span> loop as an “entry-controlled loop”. It checks the condition before entering the loop body. If the condition is not met, the code inside the loop will not be executed.
3. Fill in the Blanks
Use the <span>while</span> loop to print all integers from 10 to 1 (inclusive) and change lines after each number.
#include <stdio.h>
int main() {
int num = 10;
while (num >= 1) { // Condition expression: as long as num is greater than or equal to 1, continue looping
printf("%d\n", num);
num--; // Decrement num by 1 after each loop, counting down to 1
}
return 0;
}
Answer:
#include <stdio.h>
int main() {
int num = 10;
while (num >= 1) { // Condition expression: as long as num is greater than or equal to 1, continue looping
printf("%d\n", num);
num--; // Decrement num by 1 after each loop, counting down to 1
}
return 0;
}
Explanation:
<span>num >= 1</span>: The purpose of the loop is to print from 10 to 1. Therefore, as long as the value of<span>num</span>is greater than or equal to 1, we should continue printing. When<span>num</span>becomes 0, the condition<span>0 >= 1</span>is false, and the loop terminates.<span>num--</span>: To decrement<span>num</span>from 10 to 1, we need to subtract 1 from<span>num</span>after each loop. This is key to avoiding an infinite loop, ensuring that<span>num</span>eventually meets the loop termination condition.
4. Programming Question: Calculate Fibonacci Sequence
Write a C program that uses the <span>while</span> loop to calculate and print the first N terms of the Fibonacci sequence. The Fibonacci sequence is defined as: F(0)=0, F(1)=1, F(n) = F(n-1) + F(n-2) (n ≥ 2). The program should prompt the user to input N.
Example Input:5
Example Output:The first 5 terms of the Fibonacci sequence are: 0 1 1 2 3
Reference Code:
#include <stdio.h>
int main() {
int n, i = 0;
long long t1 = 0, t2 = 1, nextTerm; // Use long long to prevent overflow, especially when n is large
printf("Please enter the number of Fibonacci sequence terms to print (N): ");
scanf("%d", &n);
printf("The first %d terms of the Fibonacci sequence are:\n", n);
// Special handling for N being 0 or 1
if (n == 0) {
printf("No terms.\n");
return 0;
}
if (n == 1) {
printf("%lld ", t1);
return 0;
}
// Loop executes while i is less than n
while (i < n) {
printf("%lld ", t1); // Print current term
nextTerm = t1 + t2; // Calculate next term
t1 = t2; // Update t1 to old t2
t2 = nextTerm; // Update t2 to newly calculated nextTerm
i++; // Increment counter
}
printf("\n"); // Print a newline after all terms
return 0;
}
Analysis:
- Variable Initialization:
<span>n</span>is used to store the number of terms input by the user;<span>i</span>is the loop counter, starting from 0;<span>t1</span>and<span>t2</span>store the current and next terms of the Fibonacci sequence, initialized to F(0)=0 and F(1)=1. Using<span>long long</span>type is to prevent overflow when<span>n</span>is large. - User Input: Prompt the user to input
<span>n</span>. - Special Case Handling: If
<span>n</span>is 0, directly output “No terms”. If<span>n</span>is 1, only print F(0) which is 0. <span>while</span>Loop Condition:<span>while (i < n)</span><code><span>, as long as the current printed term count </span><code><span>i</span>is less than the total number of terms requested by the user<span>n</span>, continue looping.- Loop Body:
<span>printf("%lld ", t1);</span>: Print the current term<span>t1</span>.<span>nextTerm = t1 + t2;</span>: Calculate the next term based on the definition of the Fibonacci sequence.<span>t1 = t2;</span>: Assign the value of<span>t2</span>to<span>t1</span>, preparing for the next iteration.<span>t2 = nextTerm;</span>: Assign the newly calculated<span>nextTerm</span>to<span>t2</span>.<span>i++;</span>: Increment the loop counter, ensuring the loop will eventually terminate.
5. Programming Question: Reverse a Number
Write a C program that uses the <span>while</span> loop to reverse the digits of a positive integer. For example, input 12345, output 54321.
Example Input:12345
Example Output:The reversed number is: 54321
Reference Code:
#include <stdio.h>
int main() {
int num, reversed_num = 0, remainder;
printf("Please enter a positive integer: ");
scanf("%d", &num);
// Continue looping while the original number is not 0
while (num != 0) {
remainder = num % 10; // Get the last digit of the current number (units)
reversed_num = reversed_num * 10 + remainder; // Add the unit to the end of the reversed number
num /= 10; // Remove the last digit of the original number
}
printf("The reversed number is: %d\n", reversed_num);
return 0;
}
Analysis:
-
Variable Initialization:
<span>num</span>stores the original number input by the user;<span>reversed_num</span>initialized to 0, used to build the reversed number;<span>remainder</span>is used to store the last digit extracted each time. -
<span>while</span>Loop Condition:<span>while (num != 0)</span>, as long as the original number<span>num</span>is not 0, there are still digits to extract, continue looping. When<span>num</span>eventually becomes 0, it indicates that all digits have been processed, and the loop terminates. -
Loop Body Logic:
<span>reversed_num * 10</span>: Shift the currently stored number in<span>reversed_num</span>left by one position (equivalent to multiplying by 10), making room for the newly extracted unit.<span>+ remainder</span>: Add the newly extracted<span>remainder</span>to the empty unit.- Example Tracking:
- Initial:
<span>num=12345</span>,<span>reversed_num=0</span> - First:
<span>remainder=5</span>,<span>reversed_num = 0*10 + 5 = 5</span> - Second:
<span>num=1234</span>,<span>remainder=4</span>,<span>reversed_num = 5*10 + 4 = 54</span> - Third:
<span>num=123</span>,<span>remainder=3</span>,<span>reversed_num = 54*10 + 3 = 543</span> - … and so on
<span>remainder = num % 10;</span>: Use the modulus operator<span>%</span>to get the last digit of<span>num</span>. For example, 12345 % 10 results in 5.<span>reversed_num = reversed_num * 10 + remainder;</span>: This is the key step in constructing the reversed number.<span>num /= 10;</span>: Use the division operator<span>/</span>to remove the last digit of<span>num</span>. For example, 12345 / 10 results in 1234. Thus, in the next loop, the new unit becomes the old ten.
Loop Termination: When <span>num</span> is finally divided down to 0, the loop ends, and the reversed number is stored in <span>reversed_num</span>.
This problem well demonstrates the flexible application of the <span>while</span> loop in number processing, especially the technique of breaking down and reconstructing numbers through continuous modulus and division.