This program was basically a problem in an exam.
"A text file contains a list of real numbers separated by comma. Write to read the real numbers from the given text file and determine average of the numbers from the list of real numbers."
I used this code to generate the numbers as required.
Code:
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fptr;
fptr = fopen ("numbers.txt","w");
if(fptr == NULL)
{
printf("Error reading the file.");
}
fprintf(fptr,"1,2,3,4,5,6,7,8");
fclose(fptr);
getch();
}
This is what I coded to get the job done.
Code:
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fptr;
fptr = fopen ("numbers.txt","r");
if(fptr == NULL)
{
printf("Error reading the file.");
}
int count = 0, sum=0, num = 0, i,n;
while((fscanf(fptr,"%d,",&n))!=EOF)
{
count = count + 1;
sum = sum + n;
printf("check... \n"); //just to do a loop check
}fclose(fptr);
printf("The average of the given numbers are %d",sum/count);
getch();
}
Well, the program did its task. But before I got to this, I used
while((fscanf(fptr,"%d",&n))!=EOF)
[without the comma inside the quotes, i.e. "%d"]
This cause the program to loop over and over which can easily be tracked by the "check..."
I wanted to know how this difference occured.
Plus, I'd love to get suggestions regarding my programming style and alternative solutions to this problem, if it isnt much to ask.
Thank you.