dimanche 5 août 2018

C | Print Boxes inside of Boxes with only for/while loops and if/else statements

Hey so I know this question has been asked before but it hasn't been sufficiently answered.. I feel my code is pretty close but the error with mine is that the boxes print on separate lines instead of inside of each other. I'm assuming that the problem lies with my initial for-loop and am unsure as to how to adjust it. Any help would be greatly appreciated!

Here is what I need:

enter image description here

This is the code I currently have and its output:

#include <stdio.h>

int main(void) {

    int boxes;

    printf("How many boxes: ");
    scanf("%d", &boxes);


    int boxSide = boxes *3 + (boxes - 1);
    int i;
    int j;

    for (i = 0, j = 0; i < boxes; i++, j += 2) { 

        int row = 1;   

            while (row <= boxSide) {

                int column = 1;

                while (column <= boxSide) {

                    if ( (row == (j+1) && column >= (j+1) && column <= boxSide - (j+1)) ||
                         (row == boxSide - j && column >= (j+1) && column <= boxSide - (j+1)) ||
                         (column == (j+1) && row >= (j+1) && row <= boxSide - (j+1)) ||
                         (column == boxSide - j && row >= (j+1) && row <= boxSide - j) ) {

                    printf("#");

                    }

                    else {
                        printf(" ");
                    }

                column++;

                }

                row++;
                printf("\n");

            }

    }
    return 0;
}

enter image description here

Aucun commentaire:

Enregistrer un commentaire