[15 Marks] Question2 Write a C program that will read data (sales for January an
ID: 3874202 • Letter: #
Question
[15 Marks] Question2 Write a C program that will read data (sales for January and February) into two-dimensional array. The prog January and February ram wll find the total sales, the average, maximum and minimum value for The program should meet the following specifications: a) Using two-dimensional arrays named sales [101 21 for storing the data. b) The input array wil read data from the file named "sales2014.txt Refer Figure C(3). 80 74 69 73 72 65 55 98 92 81 87 90 76 88 82 74 68 70 73 62 Figure C(3): Input file “sales20 14 . txt” c) The output of is program should be displayed in the output file named "report2014.txt" as shown in Figure C(4). SALES for JAN FEB 80 69 72 74 73 65 98 81 90 92 87 7 6 82 68 73 74 70 62 Total 754 Average75.4 Maximum 92 Minimum55 775 77.5 98 62 Figure C(4): Output file "report2014.txt"Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
void main()
{
int sales[10][2], i , j;
FILE *inp, *out;
int row, col;
int totalJan = 0, totalFeb = 0, maxJan = 0, minJan = 0, maxFeb = 0, minFeb = 0;
inp = fopen("sales2014.txt", "r"); /*Open sales2014.txt in read only mode */
if(inp == NULL)
{
printf("Error, sales file not found. ");
return;
}
out = fopen("report2014.txt", "w"); /* Store the reports in file report2014.txt, so open in write mode */
fputs("SALES for JAN FEB ", out);
fputs(" ----------------- ", out);
for(row=0; row<10; row++)
{
if(1 != fscanf(inp, "%d", &i)) /* Read the report of january month */
break;
if(1 != fscanf(inp, "%d", &j)) /* Read the report of february month */
break;
fprintf(out, " %d %d ", i, j); /* Write the reports of both months into report2014.txt */
totalJan += i; /* Calculate Total for january */
totalFeb += j; /* Calculate Total for february */
/*Update the minimum and maximum for each month for each row of data*/
if(i > maxJan) maxJan = i;
if(row == 0)
minJan = i;
else if(i < minJan)
minJan = i;
if(j > maxFeb) maxFeb = j;
if(row == 0)
minFeb = j;
else if(j < minFeb)
minFeb = j;
if(feof(inp)) break; /* Stop reading if end of file is reached */
}
fputs(" ----------------- ", out);
fprintf(out, "Total : %d %d ", totalJan, totalFeb);
fprintf(out, "Average : %.1f %.1f ", (float)totalJan/row, (float)totalFeb/row);
fprintf(out, "Maximum : %d %d ", maxJan, maxFeb);
fprintf(out, "Minimum : %d %d ", minJan, minFeb);
fclose(inp);
fclose(out);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.