The code below does not deal with any numerical-integration or anything related to it — just the basic rule in evaluating a definite integral of the form Ax^2 + Bx + C. I would love to hear from you guys since I'm relatively new and still learning.
This coding exercise is meant to test what we learned for the past few weeks, so anything more sophisticated than the keywords below is probably discouraged, as well as other standard library functions.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void inputDegree(int *deg) {
printf("Enter the degree of the polynomial: ");
scanf("%d", deg);
}
void inputCoeffs(int deg, double *coeffs) {
printf("\nEnter the coefficients of the polynomial: \n\n");
for(int i = 0; i <= deg; i++) {
printf("Coefficient of degree %d: ", deg - i);
scanf("%lf", &coeffs[i]);
}
}
void inputLimits(double *lowerL, double *upperL) {
printf("\nEnter the lower limit of integration: ");
scanf("%lf", lowerL);
printf("\nEnter the upper limit of integration: ");
scanf("%lf", upperL);
}
void computeIntegralCoeffs(int deg, double *coeffs, double *integCoeffs) {
for(int i = 0; i <= deg; i++) {
integCoeffs[i] = coeffs[i] / (deg + 1 - i);
}
}
double evaluateIntegral(int degree, double *integCoeffs, double lowerLimit, double upperLimit) {
double lower = 1, upper = 1;
for(int i = 0; i <= degree; i++) {
lower += integCoeffs[i] * pow(lowerLimit, (degree + 1 - i));
}
for(int i = 0; i <= degree; i++) {
upper += integCoeffs[i] * pow(upperLimit, (degree + 1 - i));
}
return upper - lower;
}
int main() {
int degree;
double lowerLimit;
double upperLimit;
double integral;
double *coefficients = NULL;
double *integralCoefficients = NULL;
inputDegree(°ree);
coefficients = (double *)malloc((degree + 1) * sizeof(double));
integralCoefficients = (double *)malloc((degree + 1) * sizeof(double));
inputCoeffs(degree, coefficients);
inputLimits(&lowerLimit, &upperLimit);
computeIntegralCoeffs(degree, coefficients, integralCoefficients);
integral = evaluateIntegral(degree, integralCoefficients, lowerLimit, upperLimit);
printf("\n\nEvaluating the definite integral gives us the following area: \t%lf\n", integral);
free(coefficients);
free(integralCoefficients);
return 0;
}