arraysfor-loopturbo-pascal

How to make a loop that uses 3 of indexes each iteration without specifying last two iterations in turbo-pascal?


I have an array with PointType objects:

    const coords : array[0..6] of PointType = 
        ((x:220, y:410),
         (x:120, y:110),
         (x:480, y: 60),
         (x:320, y:200),
         (x:560, y:190),
         (x:390, y:360),
         (x:600, y:440));

I need to make a loop to go through all of these points, but using 3 of them in every single itteration and return to the beginning. Like this:

    arrayLength := SizeOf(coords) div SizeOf(PointType);
    for i := 1 to (arrayLength-2) 
    do begin
        WriteLn(someFunction(coords[i-1], coords[i], coords[i+1]));
    end;
        WriteLn(someFunction(coords[arrayLength - 2], coords[arrayLength - 1], coords[0]));
        WriteLn(someFunction(coords[arrayLength - 1], coords[0],               coords[1]));

Is there a proper way to make this in one action, not specifying last two itterations?


Solution

  • This should do the trick:

    arrayLength := SizeOf(coords) div SizeOf(PointType);
    for i := 0 to (arrayLength-1)
    do begin
        WriteLn(someFunction(coords[i],
                             coords[(i+1) mod arrayLength],
                             coords[(i+2) mod arrayLength]));
    end;