I learned the difference between
while and do-while long ago,
but do-while is rarely used —
I can honestly say I never used it in a problem.
So when people say
the body of a do-while loop runs at least once
I never really felt it.
What triggered this reflection was
【NYOJ】[56] Factorial factorisation (1)
and its for-loop conditionfor(int k=i; !(k%m); cnt++)
The meaning of !(k%m) puzzled me a little.
But with while and do-while in mind it falls out easily:
for(init; condition; update)
executes in this order:
flowchart TD
st[init] --> cond{condition}
cond -- yes --> op1[loop body]
cond -- no --> e[end]
op1 --> op2[update]
op2 --> cond
Not a bad flowchart, eh~ hahaha
Verification:
The init statement runs before the first test:
| |
The condition is tested before the body runs for the first time:
| |
And the do-while form:
| |
Both print n is 1.
Which verifies
the difference between for and do-while