Home > OS >  Making a bordered 2D array (C89)
Making a bordered 2D array (C89)

Time:09-17

I'm trying to make a 2D array that can be a varying size based on user input however with the code I have right now whenever the user inputs the size of the 2D array it does not print a '#' layer at the bottom of the array and the top layer is also wrong. Any suggestions to help me fix this error?

Below is the current code for this function as well as the current output based on the current parameters entered

height = 20 width = 60

any help would be appreciated.

Current output:

#include<stdio.h>
#include<stdlib.h>

/* variables */

int j, i, gameover, score;
int x, y, fruitx, fruity, flag;

/* code */

/* Function to draw a boundary */
void draw(height, width)
{
    /* system("cls"); */
    for (i = 0; i < height; i  ) {
        for (j = 0; j < width; j  ) {
            if (i == 0 || i == width || j == 0
                || j == height) {
                printf("#");
            }
            else {
                printf(" ");
            }
        }
        printf("\n");
    }
}

This is the current output (Screenshot): enter image description here

CodePudding user response:

  • void draw(height, width) is invalid C though may resolve to "implicit int" in ancient versions of C. Either way you should change to void draw(int height, int width)

  • for (i = 0; i < height; i ) { for (j = 0; j < width; j ) implies a relation between i and height and between j and width. Therefore i == width doesn't make any sense.

  • But i == height wouldn't make any sense either, since you loop i < height, that is between 0 and height - 1.

Most likely you intended something like this instead:

if (i == 0 || j == 0 || i == (height-1) || j == (width-1))

CodePudding user response:

Stop fiddling around with individual bytes (characters).

void draw( int height, int width ) {
    int i;

    // top row
    for( i = 0; i < width; i   )
        putchar( '*' );
    puts("");

    // middle rows
    for( i = 2; i < height; i   )
        printf( "*%*s\n", width - 1, "*" );

    // bottom row
    for( i = 0; i < width; i   )
        putchar( '*' );
    puts("");
}

Because speed is not a high priority the code can be even smaller

void draw( int height, int width ) {
    int i;
    for( i = 0; i <= width; i   ) putchar( i < width ? '*' : '\n' );
    for( i = 2; i < height; i   ) printf( "*%*s\n", width - 1, "*" );
    for( i = 0; i <= width; i   ) putchar( i < width ? '*' : '\n' );
}
  • Related