C Language Loop Structures: Differences Between for, while, and do-while
In C language, loop structures are an important part of controlling the flow of program execution. They allow us to repeatedly execute a block of code until a specific condition is met. This article will detail the three main loop structures: <span>for</span>, <span>while</span>, and <span>do-while</span>, and illustrate the differences between them with example code.
1. for Loop
Syntax
for (initialization; condition; update) { // loop body}
Description
- Initialization: Executed once before the loop starts, used to define and initialize the control variable.
- Condition: Checked before each iteration; if true, the loop body is executed; if false, the loop exits.
- Update: Executed at the end of each iteration, used to update the control variable.
Example Code
#include <stdio.h>
int main() { for (int i = 0; i < 5; i++) { printf("This is iteration %d\n", i + 1); } return 0;}
Output:
This is iteration 1
This is iteration 2
This is iteration 3
This is iteration 4
This is iteration 5
2. while Loop
Syntax
while (condition) { // loop body}
Description
<span>while</span>loop first checks the condition; if true, it enters the loop body and executes; otherwise, it skips directly.- When using a
<span>while</span>loop, ensure that the control variable is modified somewhere to avoid infinite loops.
Example Code
#include <stdio.h>
int main() { int i = 0;
while (i < 5) { printf("This is iteration %d\n", i + 1); i++; // Update control variable to avoid infinite loop }
return 0;}
Output:
This is iteration 1
This is iteration 2
This is iteration 3
This is iteration 4
This is iteration 5
## 3. do-while Loop
### Syntax
do { // loop body } while (condition);
### Description
<span>do-while</span>differs from<span>while</span>in that the latter checks the condition first before deciding whether to enter, while the former will execute at least once because it checks the condition at the end.
Example Code
#include <stdio.h>
int main() { int i = -1; // Initialize a value less than 5
do { printf("This is also the first output: iteration %d\n", i + 2); i++; } while (i < 5);
return 0; }
Output:
This is also the first output: iteration 2
This is also the first output: iteration 3
This is also the first output: iteration 4
This is also the first output: iteration 5
This is also the first output: iteration 6
Summary
| Feature | for | while | do-while |
|---|---|---|---|
| Initialization | Yes | No | No |
| Condition Check | Before each iteration | Before each iteration | After each iteration |
| At least run once | No | No | Yes |