QB / QB64 Discussion Forum      Other Subforums, Links and Downloads

 Return to Index  

Breaking out of deeply nested loops

April 2 2007 at 12:54 AM
Solitaire  (Login Solitaire1)

Previously, I've used a flag as a condition for breaking out of each level, but that can get rather awkward. Some would resort to a GOTO command for a clean break, but others would prefer avoiding GOTO. Here is an alternate solution.

If you have a group of nested FOR loops inside an outer DO loop, all you have to do is EXIT DO to break out of everything at once.

In fact, if you need to break out of a deeply nested FOR loop, you can even create a dummy outer DO loop. Make sure you use a condition to end the dummy loop after one repeat. For example, initialize X as 0, and LOOP UNTIL X = 0. The EXIT can be used only if necessary under certain conditions. Otherwise, it should continue executing the code without a break and you wouldn't want to get trapped inside an endless loop.

To break out of nested DO loops, you might use a dummy outer FOR loop that repeats once:
FOR x = 1 to 1

You can't use a dummy WHILE loop since there is no EXIT WHILE command and you can't place WEND inside a nested DO loop.

Example code:

FOR x = 1 TO 1
               PRINT "Inside nested DO loop"
               INPUT "Enter to continue or Q to quit:  ", E$
               IF UCASE$(E$) = "Q" THEN EXIT FOR
            LOOP UNTIL x = 10
        LOOP UNTIL x = 10
    LOOP UNTIL x = 10
PRINT "Outside FOR loop.  x = "; x
w = 0
    FOR x = 1 TO 10
        FOR y = 1 TO 10
            FOR z = 1 TO 10
                PRINT "Inside nested FOR loop"
                INPUT "Enter to continue or Q to quit:  ", E$
                IF UCASE$(E$) = "Q" THEN EXIT DO
            NEXT z
        NEXT y
    NEXT x
PRINT "Outside DO loop.  w = "; w

This message has been edited by Solitaire1 on Apr 2, 2007 6:53 AM

 Respond to this message   

 Copyright © 1999-2018 Network54. All rights reserved.   Terms of Use   Privacy Statement  

Newbies usually go to www.qbasic.com and click on The QBasic Forum
Forum regulars have their own ways, which include The QBasic Community Forums