Search code examples
objective-cfor-loopnested-loops

Explain this nested for loop?


This is creating a square with the width and height already set up and printing it out into the output using dashes, And it runs perfectly; But I don't seem to full understand what the second and third loop are doing and hows its running.

- (void)draw {
    for (int w = 1; w <= width; w++) {
        printf("-");
    }

    ***
    for (int h = 0; h <= height; h++) {
        printf("\n");
        printf("|");

        for (int space = 0; space <= width; space++) {
            printf(" ");

        }

        printf("|");
    }
    ***

    for (int w = 1; w <= width; w++) {
        if (w == 1) {
            printf("\n");
        }

        printf("-");

        if (w == width)
            printf("\n");
        }  
    }
}

Solution

  • The middle loop you are asking about basically draws the left and right side of the box, one '|' at a time, from top-to-bottom... It prints the first | on the left side, then a bunch of spaces, then the first | on the right side. It then moves down to the next line and repeats all over again.

    It's probably easier to visualize it:

    After the first loop you're left with something like this (assuming width = 15)

     ---------------
    

    Once the second starts, it inserts a newline and prints a pipe | on the left, leaving you with:

    --------------- |

    Then the inner loop inserts spaces for the amount your width is, (represented here as o) leaving you with this:

     ---------------
    |ooooooooooooooo
    

    After the spaces have been inserted, another pipe is drawn on the right side, and you're left with:

     ---------------
    |               |
    

    This continues height times until you're left with (assuming height = 5):

     ---------------
    |               |
    |               |
    |               |
    |               |
    |               |
    

    Finally, the last loop prints the bottom, just like the top:

     ---------------
    |               |
    |               |
    |               |
    |               |
    |               |
     ---------------