/* * ============================================================================ * arrays.c : The purposes of this C program are: * * (a) To read daily rainfalls for one week, and compute the range and average. * (b) Demonstrates use of one-dimensional arrays, and output to a file. * ============================================================================ */ #include #include #define max(a, b) ((a) > (b) ? (a) : (b)) /* Forward declaration of the function fileOut */ void fileOut( float faRainfall[], float fAv ); enum { MaxDays = 7 }; int main( void ) { float faRainfall[ MaxDays ]; /* store the rainfall for each day in the week: */ float fSum = 0.0; float fMax = 0.0; float fAv = 0.0; int iDay; /* day counter: */ /* [a] : initialize the rainfall for each day to zero */ for( iDay = 1; iDay <= MaxDays; iDay++ ) faRainfall[ iDay-1 ] = 0.0; /* [b] : Prompt the user for the rainfall for each day: */ for( iDay = 1; iDay <= MaxDays; iDay++ ) { printf( "Enter the rainfall (in inches) for day %d -->", iDay ); scanf( "%f%*c", &faRainfall[ iDay-1 ] ); } /* [c] : Print the maximum and average rainfall for the week: */ for( iDay = 1; iDay <= MaxDays; iDay++ ) { fMax = max( fMax, faRainfall[ iDay-1 ] ); fSum += faRainfall[ iDay-1 ]; } fAv = fSum/MaxDays; printf("\nThe maximum amount of rain this week was %f inches\n", fMax ); printf( "The average rainfall this week was %f inches \n", fAv ); /* [d] : Write details of rainfall to output file */ fileOut( faRainfall, fAv); } /* * ============================================================== * function 'fileOut' to write the data to a file called RAIN.TXT * ============================================================== */ void fileOut( float faRainfall[], float fAv ) { FILE *fpRain; /* typedef struct, defined in stdio.h */ int iDay; /* day counter */ fpRain = fopen("RAIN.TXT", "w+"); for ( iDay = 1; iDay <= MaxDays; iDay++ ) fprintf( fpRain, "%f %f \n", faRainfall[ iDay-1 ], fAv ); fclose( fpRain ); }