π C Language Loop Structures (Part 2): Detailed Explanation of while and do-while Loops
Author: IoT Smart Academy
π‘ 1. Why do we need while?
Sometimes we do not know how many times a loop should execute, for example:
- The user keeps entering data until they input 0 to end
- Repeatedly entering a password until it is correct
- The sensor continuously samples until a threshold is triggered
In this case, <span>for</span> loops are inconvenient because the number of iterations is unknown. β
while loops are more flexible!
π§± 2. Basic Syntax of while
while (condition) {
loop statements;
}
π Execution Logic:
Check β True β Execute β Check again β Execute again β β¦ β False β End
β Example 1: Output numbers from 1 to 5
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
return 0;
}
Output:
1 2 3 4 5
π Note:
- Remember to update the variable
<span>i++</span> - Otherwise, the condition will always be true β infinite loop!
β Example 2: Calculate the sum from 1 to 100
#include <stdio.h>
int main() {
int sum = 0, i = 1;
while (i <= 100) {
sum += i;
i++;
}
printf("Total sum: %d\n", sum);
return 0;
}
Output:
Total sum: 5050
β Example 3: Password verification program (Typical application)
#include <stdio.h>
#include <string.h>
int main() {
char password[20];
while (1) {
printf("Please enter the password:");
scanf("%s", password);
if (strcmp(password, "iot2025") == 0) {
printf("Login successful!\n");
break;
} else {
printf("Incorrect password, please try again.\n");
}
}
return 0;
}
π Features:
- Infinite loop
<span>while(1)</span> - Combined with
<span>break</span>to achieve βuntil correctβ
π§© 3. do-while Loop (Executes at least once)
do {
loop statements;
} while (condition);
π Execution Order:
Execute first β Check β If satisfied, continue β Otherwise, exit
β Example 1: Basic structure
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
return 0;
}
Output:
1 2 3 4 5
Similar to while, but executes at least once β
β Example 2: Input numbers until 0 is entered
#include <stdio.h>
int main() {
int n;
do {
printf("Please enter a number (input 0 to end):");
scanf("%d", &n);
if (n != 0)
printf("You entered: %d\n", n);
} while (n != 0);
printf("Program ended.\n");
return 0;
}
π Suitable for βdo first, then checkβ situations.
β Example 3: Average score input (Dynamic loop)
#include <stdio.h>
int main() {
int count = 0;
float score, sum = 0;
do {
printf("Input score (negative number to end):");
scanf("%f", &score);
if (score >= 0) {
sum += score;
count++;
}
} while (score >= 0);
if (count > 0)
printf("Average score: %.2f\n", sum / count);
else
printf("No valid scores entered.\n");
return 0;
}
π while is a typical application for unknown iterations.
βοΈ 4. Summary of Loop Control
| Control Statement | Function | Example |
|---|---|---|
<span>break</span> |
Immediately exit the entire loop | Exit after correct password |
<span>continue</span> |
Skip the current loop, proceed to the next | Skip negative inputs |
<span>while(1)</span> |
Infinite loop | Commonly used in main menus, control programs |
π« 5. Common Errors Summary
| Error Type | Example | Description |
|---|---|---|
| Infinite Loop | <span>while(1){}</span> |
Condition always true with no break |
| Condition Not Updated | <span>i</span> not incremented |
Condition always true |
| Logical Error | <span>doβ¦while(i>5)</span> |
Ends immediately after one execution |
π§ 6. Classroom Exercises (Analysis part to be published tomorrow)
π Exercise 1
Use a while loop to calculate the factorial of 1~n (n!)
Input: 5 Output: 120
π Exercise 2
Use do-while to input several positive numbers and output the maximum value. Input a negative number to end.
π Exercise 3 (Challenge)
Write a number guessing game:
- The system sets a random number between 1 and 100
- The user keeps inputting until they guess correctly
- Each time, prompt βtoo highβ or βtoo lowβ
Hint: <span>#include <stdlib.h></span>, <span>rand()</span>, <span>srand(time(0))</span>
β 7. Summary
| Loop Type | Characteristics | Scenario |
|---|---|---|
<span>for</span> |
Known number of iterations | Accumulation, traversal |
<span>while</span> |
Unknown number of iterations, check first | Dynamic loops, real-time input |
<span>do-while</span> |
Executes at least once | Menu loops, input validation |
π Next Article Preview
π₯ Comprehensive Applications of C Language Loops
- Upper right triangle of multiplication table
- Fibonacci sequence
- Comparison of accumulation and multiplication
- Random number exercises
- Comprehensive case of break + continue
π IoT Smart Academy
One article a day, programming is not difficult. From C language basics to IoT project practice, let’s learn together!πͺ