C program code for Trapezoidal Rule
1 | #include<stdio.h> | ||||
2 | #include<conio.h> | ||||
3 | #include<math.h> | ||||
4 | float f(float x) | ||||
5 | { | ||||
6 | return(1/(1+pow(x,2))); | ||||
7 | } | ||||
8 | void main() | ||||
9 | { | ||||
10 | int i,n; | ||||
11 | float xn,x0,h,y[20],se,so,ans,x[20]; | ||||
12 | printf("\n Enter the values of xn,x0,h:\n"); | ||||
13 | scanf("%f%f%f",&x0,&xn,&h); | ||||
14 | n=(xn-x0)/h; | ||||
15 | if(n%2==1) | ||||
16 | { | ||||
17 | n=n+1; | ||||
18 | } | ||||
19 | h=(xn-x0)/n; | ||||
20 | printf("\nrefined_value _of n and h are:%d %f\n",n,h); | ||||
21 | printf("\n Y values \n"); | ||||
22 | for(i=0; i<=n; i++) | ||||
23 | { | ||||
24 | x[i]=x0+i*h; | ||||
25 | y[i]=f(x[i]); | ||||
26 | printf("\n%f\n",y[i]); | ||||
27 | } | ||||
28 | so=0; | ||||
29 | se=0; | ||||
30 | for(i=1; i<n; i++) | ||||
31 | { | ||||
32 | if(i%2==1) | ||||
33 | { | ||||
34 | so=so+y[i]; | ||||
35 | } | ||||
36 | else | ||||
37 | { | ||||
38 | se=se+y[i]; | ||||
39 | } | ||||
40 | } | ||||
41 | ans=h/3*(y[0]+y[n]+4*so+2*se); | ||||
42 | printf("\nFinal_integration is %f",ans); | ||||
43 | getch(); | ||||
44 | } |
