I03 Answer


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

/* Puzzle I03 -- gray Wedge
|
|  The name of the file, the number of rows and number of columns,
|  and the gray level are specified on the command line.
|
*/

void writeWedge( FILE *image, int nrows, int ncols)
{
  int r, c, grayLevel;

  for ( r=0; r<nrows; r++ )
  {
    grayLevel = (int)(r*255)/(nrows-1) ;
    for ( c=0; c<ncols; c++ )
      fputc( grayLevel, image );
  }
}

int main(int argc, char *argv[])
{
  int  nrows, ncols ;
  FILE *image;

  /* check the command line parameters */
  if ( argc != 4 )
  {
    printf("makeGray fileName.pgm nrows ncols\n");
    return 0;
  }

  nrows = atoi( argv[2] );
  if ( nrows < 1 )
  {
    printf("number of rows must be positive\n");
    return 0;
  }

  ncols = atoi( argv[3] );
  if ( nrows < 1 )
  {
    printf("number of columns must be positive\n");
    return 0;
  }

  /* open the image file for writing */
  if ( (image = fopen( argv[1], "wb") ) == NULL )
  {
    printf("file %s could not be created\n", argv[1]);
    return 0;
  }

  /* write out the PGM Header information */
  fprintf( image, "P5 ");
  fprintf( image, "# Created by writeWedge\n");
  fprintf( image, "%d %d %d ", ncols, nrows, 255 );

  /* Write out all the pixels */
  writeWedge( image, nrows, ncols );

  /* close the file */
  fclose ( image );

  return 1;
}

Comments: The gray level varies linearly from level 0 (at row zero) to level 255. r has a maximum value of (nrows-1) and the expression

grayLevel = (255*r)/(nrows-1)

will give only that row the value 255.


back