I65 Answer ― Red Square


#include <stdlib.h>
#include <stdio.h>
const int sqRed=250, sqGreen=50, sqBlue=50;
const int bkRed=240, bkGreen=250, bkBlue=240;

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

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

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

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

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

  /* write out the PPM Header information */
  fprintf( image, "P6 ");
  fprintf( image, "%d %d %d ", ncols, nrows, 255 );
  srand( time(NULL) );

  /* write out the pixel data */
  for ( r=0; r<nrows; r++ )
    for ( c=0; c<ncols; c++ )
    {
      if ( r>nrows/6 && r<5*nrows/6 && c>ncols/6 && c<5*ncols/6 )
        {fputc( sqRed, image ); fputc( sqGreen, image ); fputc( sqBlue, image );}
      else
        {fputc( bkRed, image ); fputc( bkGreen, image ); fputc( bkBlue, image );}
    }

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

  return 1;
}

Comments: On older C compilers you might have to put the 2D arrays in static memory and define their sizes with preprocessor constants.

There are other ways to solve this puzzle. Since the blocks are output in raster order, the colors of only 8 blocks need to be known at any one time. The 8x8 arrays could be replaced with 1D arrays that hold the color values for the current block-row.