break
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.
Example 1
{ Object[] objs(); objs << 2.4 << 1 << "C" << 5; double sum; for (obj in objs) { if (obj as Number) { sum += obj.double; pln(#obj; #sum); } else { pln(eRed, "Break "; #obj, ePop); break; } } pln(#sum); }
Output:
obj=2.4, sum=2.4
obj=1, sum=3.4
Break , obj=C
sum=3.4
Example 2
{ Object[] objs(); objs << 2.4 << 1 << 2.6 << "C" << 5; double res; for (obj in objs) { if (obj as Number) { double factor1 = obj.double; for (factor2 in 1..10) { double product = factor1 * factor2; if (product > 10) { pln(eRed, "Break inner"; #product, ePop); break; } else { res += product; pln(#product; #res); } } } else { pln(eRed, "Break outer"; #obj, ePop); break; } } pln(eGreen, #res, ePop); }
Output: product=2.4, res=2.4 product=4.8, res=7.2 product=7.2, res=14.4 product=9.6, res=24 Break inner, product=12 product=1, res=25 product=2, res=27 product=3, res=30 product=4, res=34 product=5, res=39 product=6, res=45 product=7, res=52 product=8, res=60 product=9, res=69 product=10, res=79 product=2.6, res=81.6 product=5.2, res=86.8 product=7.8, res=94.6 Break inner, product=10.4 Break outer, obj=C res=94.6
continue
When a continue statement is encountered inside a loop, the flow of control is interrupted, however, iteration of the loop will be continued.
Example
{ int start; int stop = 10; int sum; while (int i = 0; i < 10; i++) { if (i%2 == 0) continue; sum += i; pln(#i; #sum); } pln("The sum of odd numbers between ", start, " and ", stop, " is ", sum); }
Output: i=1, sum=1 i=3, sum=4 i=5, sum=9 i=7, sum=16 i=9, sum=25 The sum of odd numbers between 0 and 10 is 25
goto
To transfer the control from one statement to another statement, goto can be used. The transfer can be done within the same block and there must a label, where you want to transfer the control.
The use of
goto
may lead to code that is hard to follow, so use it with caution!Example
{ Object[] objs(); objs << 2.4 << 1 << "C" << 2.6 << "Alpha" << 5; double sum; int c; if (objs.any) { TryNext: c++; pnn("Trying index ", c-1, ": "); Object obj = objs[c-1]; if (obj as Number) { pln("Adding ", obj); sum += obj.double; } else { pln("Skipping ", obj); goto TryNext; } if (c < objs.count) { goto TryNext; } } pln(c, " elements was checked. The sum of all numeric elements is ", sum); }
Output: Trying index 0: Adding 2.4 Trying index 1: Adding 1 Trying index 2: Skipping C Trying index 3: Adding 2.6 Trying index 4: Skipping Alpha Trying index 5: Adding 5 6 elements was checked. The sum of all numeric elements is 11
Comments
0 comments
Please sign in to leave a comment.