I am writing a program in Karel, which is basically Pascal plus motion commands for Fanuc robots. My code works, including looping through it 200 times with a for loop.
Now I want to add an exclusion list so in pseudocode" "for I=1 to 200 do unless I is on the exclusion list"
The list is: "array exclude[5] of integer" My code is:
for I=1 to 200 DO
FOR j =1 TO 5 DO
IF exclude[j]=i THEN
GO TO end_it
ENDFOR
bunch of code
endit::
ENDFOR
Now I know why I am getting a stack overflow, I am jumping out of the for loop. However, I can't come up with a way of how to solve my problem. I could check the 5 members of the array individually, but I am trying to keep my code short and sweet, especially since I have a second (third) for loop where I have to add the same thing again.
Any help will be appreciated!
The
GoTo()statement is generally seen as a root of all evil. It may seem like a handy thing, but it creates more problems than anyone should need to solve. And indeed, the first thing to do is to get rid of it here too.One possibility in some pascal editions is a
BREAKstatement, to break out of a loop. If KAREL doesn't support, and even if it would, I consider it better to use another kind of loop. You can use aREPEAT .. UNTIL conditionloop instead, which by nature provides for a orderly exit from a loop, as follows:This allows you to exit the
REPEAT UNTILloop immediately when you find a match in theexclude[]array. Then testing the newExcluded: booleanvariable you know whether to run thebunch of code.PS. My code example uses partly Delphi pascal syntax, hope you can deciffer it.
PS2. Just by pure curiosity I downloaded a manual,
KAREL Reference Manual v. 6.3.1and looking atA.6.3 FOR...ENDFOR Statementone of the bullets say: Never issue a GO TO statement in a FOR loop. If a GO TO statement causes the program to exit a FOR loop, the program might be aborted with a "Run time stack overflow" error. I guess you would benefit from this manual in other situations too.PS3. Take also a look at above mentioned manual, paragraph 4.2.2, which also describes the third kind of loop -
WHILE...ENDWHILE.