Summary;
| Loop | Best for |
|---|---|
for |
repeating a fixed number of times |
while |
repeating until a condition changes |
while → you control the counter manually
for → the counter is built into the loop
Q: Counter based while loop is similar to for loop. is that correct?
Yes — that’s basically correct.
A counter-based while loop and a for loop often do the same job: repeat something a certain number of times using a counter variable.
The difference is mostly how the code is organized.
while loopIn a while loop, you must create and update the counter yourself.
Example (p5.js):
let i = 0;
function setup() {
createCanvas(400, 200);
}
function draw() {
background(220);
let x = 20;
while (i < 5) {
ellipse(x, 100, 20, 20);
x = x + 60;
i = i + 1;
}
noLoop();
}
i starts at 0i < 5ifor loop (same logic)