Puzzle 2D12


Initialize a 2D array so that its diagonal is 0, elements above the diagonal are 1, and elements below the diagonal are -1

[M-10] The diagonal of a 2D array consists of the elements x[i][i] with the same row number as column number. Initialize an array of ints so that elements on the diagonal are 0, elements above the diagonal are 1, and elements below the diagonal are -1. Here are some examples:

 0  1  1  1  1 1
-1  0  1  1  1 1
-1 -1  0  1  1 1
-1 -1 -1  0  1 1
-1 -1 -1 -1  0 1
-1 -1 -1 -1 -1 0
 0  1  1  1  
-1  0  1  1  
-1 -1  0  1  
-1 -1 -1  0  
-1 -1 -1 -1  
-1 -1 -1 -1  
 0  1  1  1  1 1
-1  0  1  1  1 1
-1 -1  0  1  1 1

Here is a testing framework:

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

#define NUMCOLS 10
#define NUMROWS 10
 
void initDiagonal( int nrows, int ncols, int x[nrows][ncols]  )
{
  . . . .
}

void print2DArray ( int nrows, int ncols, int x[nrows][ncols] )
{
  int r, c;  /* row and column indexes for the array */

  /* Print elements in row major order */
  for ( r=0; r<nrows; r++ )
  {
    for ( c=0; c<ncols; c++ )
      printf("%3d ", x[r][c]  );
    printf("\n");
  }
}
 
int main(int argc, char *argv[])
{
  int x[NUMROWS][NUMCOLS];

  initDiagonal( NUMROWS, NUMCOLS, x );
  printf("\n\nInitialized:\n");
  print2DArray( NUMROWS, NUMCOLS, x );
  return 0;
}


Answer         Next Page         Previous Page Home