“From today on, study hard and make progress every day”
Repetition is the best method for memory; spend one minute each day to remember the basics of C language.
“Series of 100 Essential Knowledge Points for C Language Beginners“
29. Summary of for Loop Usage Techniques: Direct Control of Loop Count
1. Basic Structure of for Loop
The for loop is the most commonly used counting loop structure in C language, with the following syntax:
for (initialization; condition; increment) {
// loop body code
}
Execution Flow
- 1. Execute the initialization (only the first time)
- 2. Check the condition; if false, exit the loop
- 3. Execute the loop body code
- 4. Execute the increment
- 5. Return to step 2
2. Basic Usage Examples
1. Standard Counting Loop
for (int i = 0; i < 10; i++) {
printf("%d ", i);
}
// Output: 0 1 2 3 4 5 6 7 8 9
2. Reverse Loop
for (int i = 9; i >= 0; i--) {
printf("%d ", i);
}
// Output: 9 8 7 6 5 4 3 2 1 0
3. Common Techniques for for Loop
1. Multiple Variable Control
for (int i = 0, j = 10; i < j; i++, j--) {
printf("%d %d\n", i, j);
}
2. Omission of Some Expressions
int i = 0;
for (; i < 10; ) { // Equivalent to while loop
printf("%d ", i++);
}
3. Infinite Loop
for (;;) { // Classic infinite loop syntax
// Must break internally
if (condition) break;
}
4. Special Usage Techniques
1. Application of Comma Operator
for (int i = 1, sum = 0; i <= 100; sum += i, i++);
2. Complex Increment Expressions
for (int i = 2; i < 100; i *= 2) {
printf("%d ", i);
}
5. Comparison with while Loop
| Feature | for Loop | while Loop |
|---|---|---|
| Applicable Scenario | Known loop count | Condition-driven loop |
| Variable Scope | Can limit the scope of counting variable | Variable must be declared externally |
| Code Compactness | Loop control is centralized | Control statements are dispersed |
| Readability | Loop intent is clear at a glance | Condition changes are more flexible |
6. Common Errors
1. Incorrect Semicolon Placement
for (int i = 0; i < 10; i++); { // Error! Loop body is empty
printf("%d", i);
}
Correct approach:
for (int i = 0; i < 10; i++) {
printf("%d", i);
}
2. Array Out-of-Bounds Access
int arr[5];
for (int i = 0; i <= 5; i++) { // arr[5] out of bounds
arr[i] = i;
}
Correct approach:
for (int i = 0; i < 5; i++) {
arr[i] = i;
}
Some students contacted me, wanting to have a study exchange group. I hesitated to create one before due to concerns about advertisements, but I think having a group would indeed be convenient, so I will try to create one this time.
If you need it, please join quickly; the validity period is 7 days.

———- End ———-
[Special Statement: All articles in this public account are original or authorized by the author. Some content and images are sourced from the internet. Please feel free to consume them. The views are for learning reference only. If there are any errors or omissions, please forgive me.]


“If you like C, please give a thumbs up”
Click the bottom right corner to see more
“