# Break nested loops

Posted 8 years ago
8800 Views
|
7 Replies
|
1 Total Likes
|
 How can I exit multiple nested loops? Break[] exits nearest loop only. For[j = 1, j <= 10, j++, For[i = 1, i <= 10, i++, If[i == 3 && j == 4, Break[]] ]]; Print[i, j] 
7 Replies
Sort By:
Posted 8 years ago
 (how to delete the post? :))
Posted 8 years ago
 I had the same problem coming from basic and Fortran. That was procedural programming, so I was told... For loops: use Table, Nest, NestWhile, Fold, etc instead of For-Next. This is functional programming. Interrupt your "loops" by enclosing your code in a Catch and exit with Throw. It is a new habit but you learn it fast, it is faster and clear. Here is an example based on yr old style code: In[9]:= Catch[ Table[Table[{i, j}; If[i == 3 && j == 4, Throw[{i, j}]], {i, 10}], {j, 10}]] Out[9]= {3, 4} 
Posted 8 years ago
 It is not that those commands are not good but those commands were put in Mathematica version one so that people coming from a strictly procedural background dating all the way back to the beginning of Fortran would have a simple entry point into Mathematica and then move on to the more powerful constructs of the wolfram language. In the Mathematica there is always a much clearer and more powerful approach using functional and rule-based programming.
Posted 8 years ago
 Thanks. What's the reason the commands you mentioned aren't as good as Throw Catch?
Posted 8 years ago
 Throw and Catch.But perhaps you would like to move away from ancient procedural programming constructs. And things like Break, Return, GoTo, and so on are the stuff of original Fortran and Basic.
Posted 8 years ago
 That will terminate whole computation, not just exit the nested loop.
Posted 8 years ago
 Abort?