This answer includes a function printImage()
that creates an image file grayWedge.pgm from the array.
If you uncomment the statement in print2DArray()
you can create a gray wedge image file that
is viewable through IrfanView and some other image viewers:
As usual, some compilers may balk at compiling this program. You may have to do some patching.
#include <stdio.h>
#include <stdlib.h>
void grayWedge( int nrows, int ncols, int x[nrows][ncols], int low, int high )
{
int r, c, rowVal;
for ( r=0; r<nrows; r++ )
{
rowVal = ((high-low)*r)/(nrows-1) + low;
for ( c=0; c<ncols; c++ )
x[r][c] = rowVal;
}
}
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");
}
}
void printImage( int nrows, int ncols, int x[nrows][ncols] )
{
FILE *image;
int r, c;
if ( (image=fopen("grayWedge.pgm", "wb")) == NULL )
{
printf("grayWedge.pgm failed to open\n");
exit(1);
}
fprintf( image, "P5 %d %d 255", nrows, ncols);
for ( r=0; r<nrows; r++ )
{
for ( c=0; c<ncols; c++ )
fputc( x[r][c], image );
}
}
int main(int argc, char *argv[])
{
int nrows, ncols, min, max, wantImg=0;
char userInput[32];
printf( "Number of rows: ");
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);
printf( "Image File (y/n): " );
scanf("%s", userInput );
if ( userInput[0] == 'y' || userInput[0] == 'Y') wantImg=1;
int x[nrows][ncols];
grayWedge( nrows, ncols, x, min, max );
if ( wantImg )
printImage( nrows, ncols, x );
else
print2DArray( nrows, ncols, x );
}