/*
	**************************
	Patrick Schmid
	pds2
	12 March 2006
	Lab 13 Solution
	Patrick Schmid
	Section 10 & 11
	**************************
	Purpose: Read CO2 concentration for a given number of years from text file and calculate inverse
	Algorithm: For loop to read year and concentration. For loop to calculate inverse. For loop to 
			   print output table
*/

#include <fstream.h>
#include <iomanip.h>

//prototypes
void calculate(int co2[], double invco2[], double & average);

void main() {
	int year[10], co2[10]; //declare arrays with 10 items each
	int i; //declare for loop counter
	double invco2[10];  //declare array with 10 items
	char line[80]; //buffer to read line
	double average; //average CO2 concentration

	//open file
	ifstream in ("co2Function.txt", ios::in);

	//skip over first line
	in.getline(line, 80);

	//echo print setup
	cout<<"Input read from file:\n";
	cout<<"Year     CO2 concentration\n";
	cout<<"--------------------------\n";

	//read data from file using for loop (text file has 10 rows)
	for (i=0; i<10; i++) {

		in>>year[i]>>co2[i]; //read text file row into appropriate array row

		cout<<year[i]<<"     "<<co2[i]<<endl; //echo print
	
	}

	calculate(co2, invco2, average);
	
	//print table header
	cout<<"\nOutput:\n";
	cout<<"Year     CO2 concentration   Inverse of CO2 concentration\n";
	cout<<"---------------------------------------------------------\n";
	cout<<setiosflags(ios::fixed);

	//output using for loop
	for (i=0 ; i<10 ; i++) {

		cout<<setprecision(0)<<year[i]<<"     "<<co2[i]<<"            ";
		cout<<setprecision(7)<<setw(14)<<invco2[i]<<endl;	

	}

	//output average
	cout<<"Average CO2 concentration: "<<setprecision(3)<<average<<endl;
}

//void function to calculate the inverses of the CO2 concentrations
//and the average CO2 concentration
void calculate(int co2[], double invco2[], double & average) {
	int i; //for loop counter
	int sum=0; //sum of all CO2 concentrations. Need to initialize it to 0

	//calculate the inverses
	for (i=0 ; i<10 ; i++) {

		invco2[i] = 1. / co2[i]; //calculate the inverse and store it in the invco2 array
		sum+=co2[i];

	}

	//calculate average
	average = sum / 10.;
}
