The collection of N numbers is supplied in a data file called “numbers.txt”. Ass
ID: 3668762 • Letter: T
Question
The collection of N numbers is supplied in a data file called “numbers.txt”. Assume that there are no more than 1000 numbers in the file at any time. You should read these numbers into an array (auto-adjust for size via EOF detection) and compute the smallest, largest, mean, and standard deviation using 4 separate functions with the following prototypes:
double smallest(double x[], int size);
double largest(double x[], int size);
double average(double x[], int size);
double sigma(double x[], double data_avg, int size);
(Language C)
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
double smallest(double a[],int n)
{
int small,i;
small=a[0];
for(i=0;i<n;i++)
{
if(a[i]<small)
small=a[i];
}
return small;
}
double largest(double a[],int n)
{
int large,i;
large=a[0];
for(i=0;i<n;i++)
{
if(a[i]>large)
large=a[i];
}
return large;
}
double average(double a[],int n)
{
double sum=0,avg=0;
int i;
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
avg=sum/n;
return avg;
}
double sigma(double a[],double avg,int n)
{
int i;
double sdev;
for(i=0;i<n;++i)
{
sdev+=(a[i]-avg)*(a[i]-avg);
}
return (sdev/n)*(sdev/n);
}
void main()
{
double a[1000],n,s,l,avg,sig;
int i=0;
FILE *fp;
char ch;
char filename[15];
printf("enter the filename to be opened");
scanf("%s",filename);
fp=fopen(filename,"r");
if(fp==NULL)
{
printf("cant open the file");
exit(0);
}
ch=fgetc(fp);
while(ch!=EOF)
{
a[i]=(int)ch;
ch=fgetc(fp);
i++;
}
n=i;
s=smallest(a,n);
l=largest(a,n);
avg=average(a,n);
sig=sigma(a,avg,n);
}