1) Create an external file that has 10 lines with three float values on each lin
ID: 3710562 • Letter: 1
Question
1) Create an external file that has 10 lines with three float values on each line (representing 3 quiz grades).
2) Read the three values in that are on a line in from the external data file and store them in a 3 element float array. Pass the array to a function (using pointers) and find the average of the three values.
3) Assign a letter grade based on the calculated average: A for a grade >=90 and <=100 B for a grade >=80 and <90 C for a grade >=70 and <80 D for a grade >=60 and <70 F for a grade >=0 and <60
4) Print out the 3 values that were read in from the input file, the calculated average, and an assigned letter grade to a second (newly created) data file.
C PROGRAMMING
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#define MAXCHAR 1000
float average(float *grades){
return (grades[0]+grades[1]+grades[2])/3;
}
int main()
{
//File pointer
FILE *fr1,*fo1;
char str[MAXCHAR];
//File names
char file[100] = "input.txt";
char out[100] = "output.txt";
//Open both files
fr1 = fopen(&file, "r");
fo1 = fopen(&out, "w");
float grades[3],avg;
char grade;
int i;
//Read 10 lines from file
for(i=0;i<10;i++){
//Read 3 grades in a line
fscanf(fr1,"%f", &grades[0]);
fscanf(fr1,"%f", &grades[1]);
fscanf(fr1,"%f", &grades[2]);
//printf("%f %f %f ",grades[0],grades[1],grades[2]);
//Find average
avg = average(grades);
//Calculate grade
if(avg>=90&&avg<=100){
grade = 'A';
}
else if(grade>=80&&avg<90){
grade = 'B';
}
else if(grade>=70&&avg<80){
grade = 'C';
}
else if(grade>=60&&avg<70){
grade = 'D';
}
else{
grade = 'F';
}
//Write to file
fprintf(fo1, "%f %f %f %f %c ",grades[0],grades[1],grades[2],avg,grade);
}
fclose(fo1);
return 0;
}
input.txt
80 90 100
92 95 85
87 67 43
31 49 88
56 78 67
44 78 66
59 89 87
78 67 82
97 87 91
55 78 72
output.txt
80.000000 90.000000 100.000000 90.000000 A
92.000000 95.000000 85.000000 90.666664 A
87.000000 67.000000 43.000000 65.666664 D
31.000000 49.000000 88.000000 56.000000 D
56.000000 78.000000 67.000000 67.000000 D
44.000000 78.000000 66.000000 62.666668 D
59.000000 89.000000 87.000000 78.333336 F
78.000000 67.000000 82.000000 75.666664 C
97.000000 87.000000 91.000000 91.666664 A
55.000000 78.000000 72.000000 68.333336 D
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.