/*
* prog3A.c
*
* Calculates the integral of cos^2(x).
*
* Input command line argument of upper limit between 0 and Pi/2.
* Lower limit is set by default to 0.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define NODATA "There was not one argument entered. Exiting...\n"
#define INVALID "The data entered was not valid. Entered value must be between 0 and Pi/2\n"
#define LOWERLIMIT 0
#define MAXLIMIT M_PI/2
#define FILENAME "px270prog3a.dat"
#define RESULT "The integral of (Cos(x))^2 between %lf and %lf is %lf\n"
#define DEBUG 0
void integrate(double *xvalues, double *fvalues, int count, double low , double high, double *integral);
int main(int argc, char* argv[]) {
/*Values*/
double a,b,value,dummy;
double *xvalues, *fvalues,integral;
/*Counts*/
int size=0,count=0,entrycount=0;
/*Flags*/
int rightnumber=0,validInput;
/*File*/
FILE* input;
/*Set Lower Limit*/
a = LOWERLIMIT;
/*Check and then read command line arguments */
if ((argc < 2)||(argc > 2)){
printf(NODATA);
exit(EXIT_FAILURE);
}
else {
sscanf(argv[1],"%lf", &b);
}
/*Test for valid input. If not valid, exit*/
validInput = ((b > LOWERLIMIT) && (b < MAXLIMIT) && (b != EOF));
if(!validInput){
printf(INVALID);
exit(EXIT_FAILURE);
}
/*Open file, read data from file*/
input = fopen(FILENAME,"r");
/*Scan through the file once, to help work out size of array needed*/
while (rightnumber == 0){
fscanf(input," %lf ",&value);
fscanf(input," %lf ",&dummy);
count++;
printf("Count = %d \n",count);
/*If the value read for x is greater than the upper limit, stop counting data*/
if (value >= b) {
rightnumber = 1;
rewind(input);
}
}
/*Set the size of the arrays*/
size = (count+1)*(sizeof(double));
xvalues = (double*)malloc(size);
fvalues = (double*)malloc(size);
/*Use fscanf to fill arrays with values*/
while (entrycount<=count) {
fscanf(input,"%lf",&xvalues[entrycount]);
fscanf(input,"%lf",&fvalues[entrycount]);
entrycount++;
//printf("Entrycount = %lf, Xvalues = %lf, FXVALues = %lf \n",entrycount,xvalues[entrycount],fvalues[entrycount]);
}
fclose(input);
/*Call integrate function, using pointer for integral, print result*/
integrate(xvalues,fvalues,count+1,a,b,&integral);
printf(RESULT,a,b,integral);
return 0;
}
void integrate(double *xvalues, double *fvalues, int length, double lowlim , double uplim, double *integral){
double workinginteg;
int count=0;
int firstpoint=0;
while (count<length) {
/*Check if values within integration limits*/
if (xvalues[count] <= uplim){
if (xvalues[count] >= lowlim) {
if (firstpoint == 0) {
/*If the lower limit is not zero, add in the first part. If it is, this part will be zero anyway*/
if (count != 0) *integral += (xvalues[count]-lowlim)*(fvalues[count-1]);
firstpoint = 1;
}
else {
/*Add the next part of the integral*/
*integral += (xvalues[count]-xvalues[count-1])*(fvalues[count-1]);
}
}
}
count++;
}
}