Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: WHILE command


From   "Joseph Coveney" <[email protected]>
To   "Statalist" <[email protected]>
Subject   Re: st: WHILE command
Date   Mon, 17 Mar 2008 23:12:11 +0900

Vincent Davis asked about Stata's -while-:

When does it evaluate the WHILE condition?
-while- evaluates the condition at the top (beginning) of the loop.  If you
want to have the loop executed at least once regardless of the condition,
then you want a do-while or do-until loop: set up an infinite loop as Nick
Cox pointed out, and evaluate the condition of interest with an -if (!<while
condition>) continue, break- at the bottom (end) of the loop.  See Example 1
below.

If it becomes false does it immediately exit the WHILE loop?
No; program flow will not immediately exit the loop midway through if the
condition becomes false during execution of the loop--the loop will proceed
to completion before the condition is re-evaluated at the top of the next
pass.  (I interpret Vincent's question differently from how Eva and Nick
did.)  See Example 2 below.  If you want to exit the loop as soon as the
condition becomes false, then test for the false condition (with -if
(!<while condition>) continue, break-) inside the loop, immediately after
the condition is to be affected.  See Example 3 below.

I agree with Kit that -forvalues- and -foreach- are modern improvements over
the old -for-, but while loops have some advantages over for loops in
controlling program flow.  In addition -while- handles -continue, break- in
a manner consistent with most programmers' expectations.

Joseph Coveney

clear *
set more off
* Example 1
local a 1
local b 0
while (1) {
   display in smcl as result `a', `b' _newline(1)
   display in smcl as text "do-until/while loop"
   display in smcl as result `a', `++b'
   if (`a' <= `b') continue, break
}
* Example 2
local a 1
local b 0
while (`a' > `b') {
   display in smcl as result `a', `b++' _newline(1)
   display in smcl as text "If -while- exited " _continue
   display "immediately, then you wouldn't have seen this:"
   display in smcl as result `a', `b'
}
* Example 3
local a 1
local b 0
while (`a' > `b') {
   display in smcl as result `a', `b++' _newline(1)
   if (`a' <= `b') continue, break
   display in smcl as text "Immediate, midloop" _continue
   display " evaluation, and you won't see this."
}
exit


*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index