# C - A function that calculates the integral of a polynomial

I have written a simple function which takes an array of coefficients of a polynomial and then integrates it. My polynomial is represented like this: $$polynomial + polynomialx + polynomialx^2 + \dots + polynomial[n]x^n$$ And its integral will become: $$polynomialx + \frac 1 2 polynomialx^2 + \frac 1 3 polynomial x^3 + \dots + \frac{1}{n+1}x^{n+1}$$

#include <stdio.h>

void integrate(double *polynomial, double *buff, int number_of_terms) {
for(int i = 0; i < number_of_terms; i++) {
buff[i+1] = polynomial[i] / (i+1);
}
buff = 0;
}

int main(void) {
double polynomial = {1, 2, 3, 4}; // 1 + 2x + 3x^2 + 4x^3
double buff;
integrate(polynomial, buff, 4);
for(int i = 0; i < 5; i++) {
printf("%f, ",  buff[i]);
}
//Output: 0.000000, 1.000000, 1.000000, 1.000000, 1.000000
//0 + x + x^2 + x^3 + x^4
}


The problem with my solution is that I need to set the value at index zero manually - I don't think this is a good practice and therefore would like to somehow wrap the 0th index into the formula in the loop. Is there an easy way to do this?

• Thank you @TobySpeight. I have edited my question and added a minimal working example. Still, why does my question receive downvotes? – Aemilius Feb 19 '18 at 12:12
• Thanks for providing more context. Did you choose 0 for the constant term for a particular reason (e.g. to make the integral evaluate to zero at x==0)? Or is it an arbitrary choice? – Toby Speight Feb 19 '18 at 12:45
• The integration constant is missing from the second formula and that is what buff = 0; and this post is about. Recommend adding that to the formula. – chux - Reinstate Monica Feb 19 '18 at 16:18

• buff is not a meaningful name. Call it integral perhaps?

• I'd use a more mathematical degree rather than number_of_terms.

• In your approach (going from lowest to highest degree) polynomial and buff may never overlap. restrict them:

void integrate(double * restrict polynomial, double * restrict buff, int number_of_terms)

• I see no other way to deal with the integration constant but passing it as a separate parameter.

1. Amend double *polynomial --> const double *polynomial to better convey function's interface and allow calling with a const array.

2. size_t is the "Goldilocks" type to use for array indexing and array math without being excessively wide nor limiting.

3. Re-order parameters. polynomial goes with number_of_terms yet is separated by buff. Many C library functions list the result pointer parameters first "output" and then the "input".

//                v-----------------------------v
integrate(double *polynomial, double *buff, int number_of_terms)


Putting this together:

#include <stdlib.h>

void integrate(double * restrict integrated, const double * restrict polynomial,
size_t degree, double c) {
integrated = c;
for(size_t i = 0; i < degree; i++) {
integrated[i+1] = polynomial[i] / (i+1);
}
}