mercredi 2 septembre 2020

Debugging some pattern printing code in C

I'm writing code for a problem involving printing patterns of "*".

I'm trying to print out a block of N by N square (where N is a power of 3 such as 3, 9, 27...) using "*" and clear out the middle bit like so:

N=3

***
* *
***

N=9

*********
*********
*********
***   ***
***   ***
***   ***
*********
*********
*********

N=27

***************************
***************************
***************************
***************************
***************************
***************************
***************************
***************************
***************************
*********         *********
*********         *********
*********         *********
*********         *********
*********         *********
*********         *********
*********         *********
*********         *********
*********         *********
***************************
***************************
***************************
***************************
***************************
***************************
***************************
***************************
***************************

In my code, I make a N by N 2D array of "*" first, and then use the function eraseMiddle() to "carve out" the middle bit.

Here is my code:

int eraseMiddle(int n, char array[n][n]) {
    for(int i=n/3; i<2*n/3; i++) {
        for (int j=n/3; j<2*n/3; j++) {
            strcpy(&array[i][j], " ");
            //printf("empty ");
        }
    }
    return 0;
}


int main() {
    int N;
    scanf("%d", &N);
    
    //creating sqaure of size NxN
    char starsArray[N][N];
    for (int i=0;i<N;i++) {
        for (int j=0;j<N;j++) {
            strcpy(&starsArray[i][j], "*");
        }
    }
    
    eraseMiddle(N, starsArray);
    
    //test
    for (int i=0;i<N;i++) {
        for (int j=0;j<N;j++) {
            printf("%c", starsArray[i][j]);
        }
        printf("\n");
    }
    

    
    return 0;
}

Without the erasing part, the code prints out a block of solid N by N "*" just fine. However, when the erasing function is used, it prints it out as so:

9
*********
*********
*********
***   **
***   **
***   **
*********
*********
*********
Program ended with exit code: 0

The absence of the last star in the line occurs for greater inputs as well.

I can't seem to understand what's wrong with the code I've written.

If anyone could help, I'd be very grateful.

Aucun commentaire:

Enregistrer un commentaire