Skip to content

Force the for loop to stop

5 messages · Salih Tuna, Stephan Kolassa

#
Hi,

you could set a dummy variable to FALSE outside the outermost loop. If 
the break condition is met in the inner loop, set the dummy variable to 
TRUE before breaking and test its truth status in the outer loop.

HTH
Stephan


Am 01.06.2011 21:25, schrieb Salih Tuna:
#
Hi Salih,

here you go:

############################################
dummy <- FALSE
for ( ii in 1:5 ) {
   for ( jj in 3:6 ) {
     cat("ii=",ii,"; jj=",jj,"\n",sep="")
     if ( ii == jj ) {
       dummy <- TRUE
       break
     }
   }
   if ( dummy ) break
}
###########################################

Note that I am using "ii" and "jj" as loop indices, not "i" and "j". 
This makes it a lot easier to search for the loop counter in more 
complex scripts - if you just search for "i", most of your hits will be 
something else than the loop counter.

HTH,
Stephan


Am 01.06.2011 22:06, schrieb Salih Tuna: