# Thread: calculate the average value from a text file

1. ## calculate the average value from a text file

Hello, I try to write a code to calculate the average value from a text file but the dumb thing is I has to count the no. of data manually to initialize the array. (here is 1000).

Here is the code:
Code:
```#include <stdio.h>
#include <stdlib.h>

int main(){

FILE *p;
p = fopen("myfile.txt", "r");

int Array;
int i;
double sum=0.0;

for (i = 0; i < 1000; i++)

{
fscanf(p, "%d", &Array[i] );

printf("Number is: %d\t %d\n\n", Array[i],i);

sum = sum + Array[i];
}
printf("The average weight is %lf",sum/1000);

fclose(p);

return 0;
}```
It works but i just want it to count the no. of data automatically. So i search something that capable to count the no. :

Code:
```#include<stdio.h>

int main(void)
{
FILE *p;
char ch;
int w=0;

p=fopen("myfile.txt","r");
if(p==NULL)
{
}
else
{
ch=fgetc(p);
while(ch!=EOF)

{

printf("%c",ch);
if(ch==' '||ch=='\n')
{
w++;
}
ch=fgetc(p);
}
printf("\nWords in a file are=%d",w);
}
fclose(p);
getch();

return 0;
}```
How do I combine the two and make use of the 'w' in the first program? I've tried but fail. Hope someone can guide me. 2. You could do something like
Code:
```int count = 0, value, sum = 0;
while ( fscanf(p, "%d", &value ) == 1 ) {
sum += value;
count++;
}``` 3. ## Thank you so much! Originally Posted by Salem You could do something like
Code:
```int count = 0, value, sum = 0;
while ( fscanf(p, "%d", &value ) == 1 ) {
sum += value;
count++;
}```
Thank you so much! It works well !

#include <stdio.h>

Code:
```int main(){

FILE *fpr;
fpr = fopen("elephant_seal.txt", "r");

int count = 0, value;

double sum = 0.0;

while ( fscanf(fpr, "%d", &value ) == 1 ) {
sum += value;
count++;
}

printf("The average weight is %lf",sum/count);

fclose(fpr);

return 0;

}``` 4. Thank you! it works well. I am obsessed in assigning those value into array but turn out it is not necessary. 5. You could keep 'sum' as integer (with more precision then individual values) and just convert to 'long double' (which have the same precision, in bits, as 'long long') when you calculate the mean:

Code:
```#include <stdio.h>
#include <stdlib.h>

int main( void )
{
// using 'long long' for 'sum', which have 2 times the precision of an 'int', in bits.
long long sum;
unsigned int count;
int value;
FILE *f;

if ( !( f = fopen( "elephant_seal.txt", "r" ) ) )
{
fputs( "ERROR opening file.\n", stderr );
return EXIT_FAILURE;
}

count = 0;
sum = 0LL;

while ( fscanf( f, "%d", &value ) == 1 )
{
sum += value;
count++;
}

fclose( f );

if ( ! count )
{
fputs( "ERROR: Couldn't read any values!\n", stderr );

return EXIT_FAILURE;
}

// Need to be 'long double' since 'double' has only 53 bits of precision!
printf( "The average weight is %.3Lf", ( long double )sum / count );

return EXIT_SUCCESS;
}``` Popular pages Recent additions #include, average, count, file, int 