![]() |
VOOZH | about |
For Loop,While Loop, and Do-WhileLoop are different loops in programming. A For loop is used when the number of iterations is known. A While loop runs as long as a condition is true. A Do-While loop runs at least once and then continues if a condition is true.
for loop is used when you know in advance how many times you want to execute the block of code.variable) takes the value of each item in the sequence during each iteration.for (initialization; condition; increment/decrement) {
// Code to be executed repeatedly
}
0 1 2 3 4
while loop is used when you don’t know in advance how many times you want to execute the block of code. It continues to execute as long as the specified condition is true.The syntax of a while loop is straightforward:
while (condition){
# Code to be executed while the condition is true
}
0 1 2 3 4
do {
// body of do-while loop
} while (condition);
Final value of count = 6
| Feature | for Loop | while Loop |
|
|---|---|---|---|
Syntax | for (initialization; condition; increment/decrement) {} | while (condition) { } | do { } while (condition); |
| Initialization | Declared within the loop structure and executed once at the beginning. | Declared outside the loop; should be done explicitly before the loop. | Declared outside the loop structure |
| Condition | Checked before each iteration. | Checked before each iteration. | Checked after each iteration. |
| Update | Executed after each iteration. | Executed inside the loop; needs to be handled explicitly. | Executed inside the loop; needs to be handled explicitly. |
| Use Cases | Suitable for a known number of iterations or when looping over ranges. | Useful when the number of iterations is not known in advance or based on a condition. | Useful when the loop block must be executed at least once, regardless of the initial condition. |
| Initialization and Update Scope | Limited to the loop body. | Scope extends beyond the loop; needs to be handled explicitly. | Scope extends beyond the loop; needs to be handled explicitly. |