for, (do-)while — How the Loop Body Executes

Words: 260

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 condition
for(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:

cpp
1
2
3
4
5
6
7
#include<stdio.h>
int main() {
	int n=1; 
	for(int i=n=0; i<0; n++,i++);
	printf("n is %d\n",n);
	return 0;
}

The condition is tested before the body runs for the first time:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include<stdio.h>
int main() {
	int n=0;
	for(int i=0; i<0; i++)
		n++;
//	for(int i=0; i<1; i++)
//		n++;
	printf("ran %d times\n",n);
	return 0;
}

And the do-while form:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include<stdio.h>
int main() {
	int n=0;
	int i=0;
	do {
		n++;
		i++;
	} while(i<0);
//	do {
//		n++;
//		i++;
//	} while(i<1);
	printf("n is %d\n",n);
	return 0;
}

Both print n is 1.

Which verifies
the difference between for and do-while

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...