Trapezoidal Rule in C

Looking for some help with my code. I'm new to learning c and either my arrays or my loop is not computing properly. This is a trapezoidal rule program and my calculation for the area is 241.667 but my results are coming out to be like 57900.0000. Can someone help me out on this code?

#include <stdio.h>
#include <math.h>

int main(void)
{
int i, j, n=6;
double coeff[6] = {1, 2, 2, 2, 2, 1};
double y[6] = {1, 7, 23, 55, 109, 191};
double a=0, b=5, h, Sum=0, Area;

{
h = (b-a)/2*(n);
}
for (i=0; i<n; i++)
{
for (j=0; j<n; j++)
{
Sum += coeff[i]*y[j];
}
}
{
Area = Sum*h;
}
printf("The definite integral is %lf \n", Area);
return 0;
}
Can you explain what is Trapezoidal Rule?
Please use code tags. http://www.cplusplus.com/articles/jEywvCM9/

I don't know what formula you have been taught for the trapezoidal rule, but I was taught using this mnemonic: h/2{ (first + last) + 2(rest) }.

1
2
3
4
5
6
7
int n = 6;
double y[6] = {1, 7, 23, 55, 109, 191};
double a = 0, b = 5, h = (b - a)/n, rest = 0, area = 0;

for( int i = 1; i < n-1; i++ ) rest += y[i];

area = h/2 * (y[0]+y[n-1] + 2*rest);


area = 241.667


edit: Output doesn't seem to match your calculation. What is the equation of the function?
edit2: Fixed a stupid mistake. Calculation is now correct.
Last edited on
It is a numerical integration method for calculating the area of the trapezoids under a function f(x) dx from a to b which is equivalent to (b-a)/2n * (y0 + 2*y1 + 2*y2 + ... + yn)
Can you show me a calculation example?
@SakurasouBusters
Let's say you were asked to find the area bound by the curve y = x², from x = 0 to x = 5, using 5 sub-intervals (using the trapezoidal rule, of course)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
y = x²

a = 0	b = 5	n = 5	h = (b - a)/n
                          = 1

x | 0 | 1 | 2 | 3 | 4  | 5 |
y | 0 | 1 | 4 | 9 | 16 | 25 |

area = h/2{ (first + last) + 2(rest) }
     = 1/2{ (0 + 25) + 2(1 + 4 + 9 + 16) }
     = 1/2{ 25 + 60 }
     = 42.5 u²

now if we were to find the definite integral of y = x²,
from x = 0 to x = 5, we would get 41.67, which is really close
to the result from the approximate trapezoidal rule
*/
There are multiple ways to calculate it. I tried a program with that equation before but was still coming out with an incorrect answer. I had some errors in my loop it looks like and my logic. Thanks for the help!
Topic archived. No new replies allowed.