do Statement

Sometimes, instead of having a loop in which the testing is done at the beginning of the loop, the testing is done at the end of the loop. This means that the loop will always be executed at least once, even if the condition was false before the loop started.

This is called the "do", or the "do" ... "while" loop. Its general syntax is:

	do s;
	while (e);

which in words is - execute (do) statement 's' while expression 'e' is true.

If 's' is a block of statements we would have:

	do {
		s1;
		...
		s2;
	} while (e);

This can be expressed with an "if" and "goto" identically as:

	loop_top:
	s;
	if (e)
	   goto loop_top;

It is clear in this form why statement 's' must be executed at least once.

The flow chart for the "do" ... "while" statement is:

          |
          v
          +---<-----------\
          |               |
          v               |
        +---+             |
        | s |             |
        +---+             |
          |               |
          v               |
          ^               |
         / \              |
        < e >->-----------/
         \ / T
          v
          | F
          v
          |

© 1991-2008 Prem Sobel. All Rights Reserved.