Puzzle 2D16


Puzzle D16 — Zero the edges of an Array

[M-10] Write a function that clears to zero all the edge elements of an MxN matrix. Those are the elements that are in row 0, column 0, row M-1, or column N-1. For example:

Original:
  0   1   2   3   4   5   6   7   8   9
 10  11  12  13  14  15  16  17  18  19
 20  21  22  23  24  25  26  27  28  29
 30  31  32  33  34  35  36  37  38  39
 40  41  42  43  44  45  46  47  48  49

Edge Zeroed:
  0   0   0   0   0   0   0   0   0   0
  0  11  12  13  14  15  16  17  18   0
  0  21  22  23  24  25  26  27  28   0
  0  31  32  33  34  35  36  37  38   0
  0   0   0   0   0   0   0   0   0   0

Here is a testing framework:

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

void zeroEdges ( int nrows, int ncols, int x[nrows][ncols] )
{
  . . .
}

/* Generate a random integer  min < = r < = max */ 
int randInt( int min, int max )
{
  return rand()%(max-min+1) + min ;
}

void fill2Drandom( int nrows, int ncols, int x[nrows][ncols], int low, int high )
{
  int r, c;
  for ( r=0; r<nrows; r++ )
  {
    for ( c=0; c<ncols; c++ )
       x[r][c] = randInt( low, high );
  }
}

void print2DArray ( int nrows, int ncols, int x[nrows][ncols] )
{
  int r, c;
  
  for ( r=0; r<nrows; r++ )
  {
    for ( c=0; c<ncols; c++ )
      printf( "%3d ", x[r][c] );
    printf("\n");
  }
}
 
int tester( int nrows, int ncols ) 
{
  int x[nrows][ncols];
  
  fill2Drandom( nrows, ncols, x, 0, 125 );
  printf("\n\nOriginal:\n");
  print2DArray( nrows, ncols, x );
  
  zeroEdges( nrows, ncols, x );
  printf("\n\Edged:\n");
  print2DArray( nrows, ncols, x );
  return 0;
}

int main(int argc, char *argv[])
{
  int nrows, ncols, rot;
  
  printf("Number of rows: ");
  scanf("%d", &nrows);
  printf("Number of cols: ");
  scanf("%d", &ncols);
  tester( nrows, ncols );  
}



Previous Page        Answer         Next Page         Home