You are on page 1of 1

#include <stdio.

h>

int main(){
FILE *fp; //use to manipulate the file
int num; //will store each grade
int counter;//this variable will be used to count the number of iterations
int total=0;
float avg;
fp=fopen("in.dat","w");//we are opening the file in.dat for writing
/*
there are three main modes
w- writing
r- reading
a- append (adds to end of file)
*/
if (fp==NULL){
printf("File not opened!\n");
}else{
for (counter=1;counter<=10;counter++){//started at 1 and ended at 10
(could also use 0 and end at 9)
printf("%d.Enter A Number: ",counter);
scanf("%d",&num);
fprintf(fp,"%d\n",num);
//fprintf(file_pointer,conv_specifier,variable)

}
}
fclose(fp);//good programming practise to close file before changing the
mode
fp=fopen("in.dat","r");//open the same file for reading
fscanf(fp,"%d",&num);
while (!feof(fp)){//while not end of file fp
total+=num;
fscanf(fp,"%d",&num); //fscanf(file_pointer,conv_spec,&var). use &
when it is a numeric variable (int ,float)
}
avg=total/10;
printf("Average is: %.2f",avg);//limit the answer to two places
}

You might also like