Thread: array issue
View Single Post
Old Apr 29th, 2008, 9:33 PM   #2
derzok
Newbie
 
Join Date: Jan 2008
Posts: 3
Rep Power: 0 derzok is on a distinguished road
Re: array issue

Here's something that does pretty much the same thing. I wrote it earlier this semester for my principle of programming languages class:
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <exception>
using namespace std;

// Parses the input file into the array's size and contents.
// Dynamically allocates memory for the array, fills it, and returns.
void parse_file(char * filename, double *&a, int &size) {
	ifstream myfile;
	myfile.exceptions( fstream::failbit );

	// Get the file name, and try to open the said file
	printf("Input the filename: ");   
	scanf("%s",filename);
	// Try opening the file, if it doesn't exist, throw an exception
	try {
		myfile.open(filename);
	} catch(ifstream::failure e) {
		printf("File does not exist or is unreadable\n");
	}

        // Read the first thing from the file as an int and store it as 'num'
	myfile>>size;

        // allocate an array to the exact that we need
        a = (double *) malloc(size*sizeof(double));
        // Fill the array
        for(int i=0; i<size; i++) {
		myfile>>a[i];
        }
	myfile.close();
}

// Standard way of calculating average
// Sums the elements of a, puts them into total, divides by size and returns.
double find_average(double *&a, int size) {
	double total = 0;
	for(int i=0; i<size; i++) {
		total = total + a[i];
	}
	return (total/(double)size);
}

// Standard way of calculating standard deviation
// Sums the square of each element minus the average
// Divides the total of squares by the size and returns the positive square root of the sum.
double find_standard_dev(double *&a, int size, double average) {
	double dev = 0;
	for(int i=0; i<size; i++) {
		dev = dev + pow(a[i]-average,2);
	}
	dev = dev/size;
	return (sqrt(fabs(dev)));
}

int main() {

	// Set up some variables
	char filename[50]; // 50 characters for the filename should be good enough unless the path is included.
	double average = 0, standard_dev = 0; // Zero out our variables before we start using them
	int num; // Array size
	double * array; // Make a pointer to our array

	parse_file(filename, array, num);

	average = find_average(array,num);

	standard_dev = find_standard_dev(array, num, average);

	printf("Average: %lf\n",average);
	printf("Standard Deviation: %lf\n",standard_dev);
	free(array);
	return 0;
}
derzok is offline   Reply With Quote