Hi. I have written a program to import a data file and print out the data set. The program should then sort the data by value, reprint it and find mean, stdev and create a histogram. The problem is that when it goes to sort the data and reprint it, it is repeats certain values instead of printing each once. It's getting mixed up. Thanx for any advice...
Code:
#include <iostream.h>
#include <math.h>
#include <iomanip.h>
#include <fstream.h>
void print_out(double a[100],int N); //prototype
void sort(double a[100], int N);
int main()
{
double a[100];int i,N,j,his[50]={0};
cout<<"Type in the number of data points"<<endl;
cin>>N;
if(N<=64){ //Read in data from file4.dat
ifstream source;
source.open("file4.dat");
if(!source)
{cerr<<"Can't open data file."<<endl;
return(1);}
for(i=0;i<N;i++)
{source>>a[i];}
source.close();}
else{cerr<<"Too many data points."<<endl;
return (1);}
print_out(a,N);
//line30
sort(a,N);
double sum1,average;
sum1=0.0; //Output the average value of the data set
for(i=0;i<N;i++)
{sum1=sum1+a[i];}
average=sum1/N;
cout<<"average value = "<<average<<endl;
double delta,sqrdelta,sum2,stdev;
sum2=0.0; //Output the standard deviation of the data set
for(i=0;i<N;i++)
{delta=a[i]-average;
sqrdelta=delta*delta;
sum2=sum2+sqrdelta;}
stdev=sqrt(sum2/(N-1));
cout<<"standard deviation of the set is "<<stdev<<endl;
double xstart,delx;int icol=0,icolmax; //Histogram
cout<<""<<endl;
cout<<"Type in the low boundary of the histogram."<<endl;
cin>>xstart;
cout<<"Type in the x-axis increment for the histogram (delta x value)."<<endl;
cin>>delx;
for(i=0;i<=N;i++)
{icol=(a[i]-xstart)/delx;
his[icol]=his[icol]+1;
icolmax=(a[N-1]-xstart)/delx;
}
//Print out histogram
//x1 is the low end for each histogram column, x2 is the high end
double x1=xstart,x2=xstart+delx;
for(i=0;i<=icolmax;i++)
{cout<<"From "<<x1<<" to "<<x2<<" there are "<<his[i]<<" measurements"<<endl;
x1=x1+delx;
x2=x2+delx;}
return 0;}
//function print_out
void print_out(double a[100],int N)
{int k,j=0,i=0,colnum=8;
cout<<"Unsorted data."<<endl;
for(j=0;j<N;j=j+colnum)
{k=colnum;
if((j+colnum)>N)
{k=N-j;}
for(i=0;i<k;i++)
{cout<<setw(8)<<a[i+j];}
cout<<""<<endl;}}
void sort(double a[100],int N)
{double temp;int i,j,k,colnum=8;
cout<<"Sorted data."<<endl;
for(i=0;i<N-1;i++)
{for(j=i+1;j<N;j++)
{if(a[j]<a[i])
{temp=a[j];a[j]=a[i];a[i]=temp;}}}
for(j=0;j<N;j=j+colnum)
{k=colnum;
if((j+colnum)>N)
{k=N-j;}
for(i=0;i<k;i++)
{cout<<setw(8)<<a[i+j];}
cout<<endl;}}