1. ## trapezoidal rule

Hi
i'm new here so sorry if i put in the code the wrong way
In class on friday I we were doing the trapezoidal rule and the lecturer told us to create a c programe which takes in five values for x and five values for y and then work out the answer.
The equation to is f(x) = .5*h*(f0 + 2*f1 + 2*f2 + ... + 2*fn-1 + fn). (where h is just x1 - x0)
I have created a programe that does it but i want to change it so it can be used for any sized sample.
I have created a matrix that asks how many y values do you want to put in and then puts in the y values.
What i would like some help with is how do i adjust the equation so it can calculate any number of y's instead of just 5?
The code i have below gets you to put in how many y's and but the equation will still only work out 5 y values
Any help would be great

Code:
```
#include <stdio.h>

double trapezoidal (double arrayy[], double arrayx[], double h);
int arraysize;
int main (void)
{
int a,b;
double f,arrayx[2],arrayy[100], ans, h,j,g;

printf("Enter arraysize: ");
scanf ("%d", &arraysize);

for (a= 0; a < 2; a++)
{
printf ("Enter a value x%d:", a);
scanf("%lf", &arrayx[a]) ;
}
printf("\n");

for (b= 0; b < arraysize; b++)
{
printf ("Enter a value y%d:", b);
scanf("%lf", &arrayy[b]) ;
}

ans = trapezoidal (arrayy,arrayx,h);

system ("pause");
return 0;

}

double trapezoidal (double arrayy[], double arrayx[], double h)
{
double f,ans;
int a,b;
h= arrayx[1] - arrayx[0];
printf("Value for h is:%lf",h);

system ("pause");
ans =(.5)*h*(arrayy[0] + 2*arrayy[1] + 2*arrayy[2] + 2*arrayy[3] + 2*arrayy[4] + 2*arrayy[5] + arrayy[arraysize]);   // works out the answer

return ans;
}```
Hope it is better now

2. Announcements - General Programming Boards
Have another go at posting your code, so it isn't on one line.
Try editing it first, rather than posting again.

3. How does the code, which seems to be in code tags, end up all on one line?

4. I dont no how i did it, but i have changed it now (hopefully)

5. Instead of hard-coding the formula, simply put a 'for' loop indexing the array. But your algorithm still needs help. You aren't using any of the arrayx.

6. Originally Posted by nonoob
Instead of hard-coding the formula, simply put a 'for' loop indexing the array. But your algorithm still needs help. You aren't using any of the arrayx.
I only use the x array for calculate h which is just x1 - x0

In gerneal how would i do the for loop indexing the array?
I dont think we have done something like that in class yet (i could be wrong do)

7. Well you are already using arrays to input values. Use similar idea for the formula: something like
ans =(.5)*h*(arrayy[0] + 2*arrayy[1] + 2*arrayy[2] + 2*arrayy[3] + 2*arrayy[4] + 2*arrayy[5] + arrayy[arraysize]);
Code:
```tot = 0;
for (i = 0; i < arraysize; i++) {
total += 2 * arrayy[i];
}
ans = 0.5 * h * tot;```

8. Originally Posted by nonoob
+ arrayy[arraysize-1]
Minus one.

Quzah.

9. Indeed. I copied from original post.