Puzzle 2D17


Create a Gray Wedge

[M-10] Write a function that fills the first row of an array with value min and the last row with value max, and the rows inbetween with values that increase linearly from min to max. The user enters min and max so the program will have to calculate the value for each row. Some Examples:

Number of rows: 10
Number of cols: 10
Value for row 0: 0
Value for row 9: 25

  0   0   0   0   0   0   0   0   0   0
  2   2   2   2   2   2   2   2   2   2
  5   5   5   5   5   5   5   5   5   5
  8   8   8   8   8   8   8   8   8   8
 11  11  11  11  11  11  11  11  11  11
 13  13  13  13  13  13  13  13  13  13
 16  16  16  16  16  16  16  16  16  16
 19  19  19  19  19  19  19  19  19  19
 22  22  22  22  22  22  22  22  22  22
 25  25  25  25  25  25  25  25  25  25
Number of rows: 7
Number of cols: 5
Value for row 0: 50
Value for row 6: 120

 50  50  50  50  50
 61  61  61  61  61
 73  73  73  73  73
 85  85  85  85  85
 96  96  96  96  96
108 108 108 108 108
120 120 120 120 120

The elements of the array are ints, so you will need to worry about integer math. Here is a testing framework.

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

void grayWedge( int nrows, int ncols, int x[nrows][ncols], int low, int 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 main(int argc, char *argv[])
{
  int nrows, ncols, min, max, wantImg=0;
  char userInput[32];
  
  scanf("%d", &nrows);
  printf( "Number of cols: ");
  scanf("%d", &ncols);
  printf( "Value for row 0: ");
  scanf("%d", &min);
  printf( "Value for row %d: ", nrows-1);
  scanf("%d", &max);

  int x[nrows][ncols]; 
  grayWedge( nrows, ncols, x, min, max );
  print2DArray ( nrows, ncols, x );
  return 0;
}


Previous Page        Answer         Next Page         Home