Loop with multiple headers

Tony Ruth Source

I frequently run into problems where the same code inside a loop is repeated, but several loops are needed. A simple example is moving around the edge of a square.

/*This code moves the variables x and y around the outside of a square counterclockwise starting from the origin.*/
for(y=0,x=0,x<width;x++);
for(,y<width;y++);
for(,x>0;x--);
for(,y>0;y--);

However, usually you need to do something with the coordinates of the square repeatedly. That means making 4 separate scopes with the same code repeated in each. Is there some code that allows you to use multiple sequential looping conditions? That code might look like this:

[  for(y=0,x=0,x<width;x++),    for(,y<width;y++),    for(,x>0;x--),    for(,y>0;y--)  ]
{
    //Do something over the perimeter of the square E.g. color in a pixel 
}

I know there are iterators, but I think they are cumbersome compared to being able to concatenate loops. Are there any languages that do have a repeated loop structure like this?

c

Answers

answered 3 months ago Dagan #1

As for your specific question - there isn't anything that implementes that directly AFAIK but.. I wrote some code in the university for this issue and maybe you can use that as a basis

basically you can calculate the coordinates from a single iterator - it's a nasty code but maybe it will help with your issue

It will print out the square coordinates of a 10x10 square (1 indexed)

#define WIDTH 10
int main()
{
    int iter = 0;
    int x = 0,y = 0;
    while ( iter < (WIDTH*4) ) {
        if ( iter < WIDTH ) {
            x = iter;
            y = 0;
        } else if ( iter >= WIDTH && iter < ( 2 * WIDTH ) ) {
            x = WIDTH -1;
            y = (iter % WIDTH) ;
        } else if ( iter >= (2 * WIDTH) && iter < ( 3 * WIDTH ) ) {
            x = (WIDTH) - (iter - (2 * WIDTH)) - 1;
            y = WIDTH - 1;
        } else {
            x = 0;
            y = (4 * WIDTH) - iter - 1;
        }
        printf("(%d, %d) ", x+1 ,y+1 );
        iter++;
    }
    printf("\n");

    return 0;
}

NOTE: the corner coordinates are repeated

comments powered by Disqus