0

The following code creates a hollow rectangle with 2D-Array.

int main(){
int x,y;
    for(x=0; x<11; x++)
        for(y=0; y<11; y++)
            if (x==0 || x==10 || y==0 || y==10)
                box [x][y] = '=';
            else{
                box[x][y]=' ';
            }
}

The if functions creates the border and the else functions creates the hollow space within it.

Is it possible to do this without the letting else add blanks into my array?

Simply getting rid of the else condition fills the supposedly empty spaces full of weird characters.

Raph
  • 103
  • 7
  • 2
    Well you *could* initialize the matrix with all spaces to begin with. But besides that, how else would you create the "hollow ***space***"? Also, why don't you want the `else` clause? What's wrong with it? – Some programmer dude Nov 18 '17 at 11:55
  • You could initialize to all spaces with `memset`. Then just fill in the borders. – 001 Nov 18 '17 at 11:58
  • @Someprogrammerdude I'm running this in a loop and everytime the loop repeats the content within turns into spaces again. – Raph Nov 18 '17 at 12:01

1 Answers1

0

Simply getting rid of the else condition fills the supposedly empty spaces full of weird characters.

Since box appears to be a global variable, its content is initially initialized to all zeros (why?)

You want the content to be initialized to spaces, so you need to do one of the following:

  • Write a loop to pre-fill box[][] with spaces, or
  • Use memset to pre-fill box[][] with spaces, or
  • Keep the else branch, which fills unused box[][] cells with spaces.

I would prefer the last solution as the most economical. I would also rewrite the loop with a conditional expression, like this:

for(y=0; y<11; y++) {
    box [x][y] = (x==0 || x==10 || y==0 || y==10) ? '=' : ' ';
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • The reason I don't want to use the `else` statement is that this function runs within a `do`...`while` loop and every time I update the content of the array and the loop repeats, this functions clears the content. – Raph Nov 18 '17 at 12:04
  • @Raph The use one of two other approaches (e.g. call `memset(box, ' ', sizeof(box))` before your loop). – Sergey Kalinichenko Nov 18 '17 at 12:10