0

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!

Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89
DeucesAx
  • 3
  • 1

2 Answers2

0

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 BREAK statement, 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 a REPEAT .. UNTIL condition loop instead, which by nature provides for a orderly exit from a loop, as follows:

for I=1 to 200 DO
  Excluded := False
  j := 0
  REPEAT
    J := J + 1
    IF exclude[j]=i THEN
      Excluded := True
  UNTIL (J = 5) or Excluded

  if not excluded then
  begin

    bunch of code

  end

ENDFOR

This allows you to exit the REPEAT UNTIL loop immediately when you find a match in the exclude[] array. Then testing the new Excluded: boolean variable you know whether to run the bunch 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.1 and looking at A.6.3 FOR...ENDFOR Statement one 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.

Tom Brunberg
  • 20,312
  • 8
  • 37
  • 54
0

Tom is right about the "go to". It should be avoided at all cost.

If I understand properly... this is an easy solution, but really not elegant:

FOR i=1 to 200 DO
    FOR j =1 TO 5 DO
        IF exclude[j]=i THEN
            -- DO nothing, but if you want to break here just set j= 5
        ELSE
            -- DO a bunch of things here
        ENDIF
     ENDFOR
ENDFOR
guidam313
  • 1
  • 1