A number of definite integrals need to be solved in applied mathematics, physics and engineering. The manual analytical solution of definite integrals is quite cumbersome and time consuming. So, in this post I have presented source code in C program for Trapezoidal method as one of the computer-programming-based solutions of definite integrals. The techniques of numerical methods are used to solve this equation; it involves a number of calculations and efforts have been made to minimize error in the program.
The trapezium or trapezoidal rule can be used as a way of estimating the area under a curve because the area under a curve is given by integration. So, the trapezoidal rule gives a method of estimating integrals. This is useful when you come across integrals that you don’t know how to evaluate. So, the program for trapezoidal method in C given here is applicable to calculate finite integral or area under a curve.
The basic working principle of the trapezoidal method c program is that trapezoidal method splits the area under the curve into a number of trapeziums. Then, area of each trapezium is calculated, and all the individual areas are summed up to give the total area under the curve which is the value of definite integral.
In the above figure, area under the curve between the points x0 and xn is to be determined. In order to determine the area, we divide the total interval (xn– x0) into ‘n’ small interval each of length ‘h’:
After that, the C source code for trapezoidal method uses the following formula to calculate the value of definite integral:
float f(float x)
printf("\n Enter values of x0,xn,h:\n");
printf("\nrefined value of n and h are:%d %f\n",n,h);
printf("\n Y values \n");
for(i=0; i<=n; i++)
for(i=1; i<n; i++)
printf("\nfinal integration is %f",ans);
The aforementioned source code for trapezoidal method is short and simple to understand. It uses a user defined function to calculate the value of function i.e f(x) =1 /(1 + x2). The variable data type used in the program are integer and float types. There are only three variables to be input to the program – x0 ( initial boundary value), xn ( final boundary value) and h (strip length).
As the C program for Trapezoidal Method is executed, it asks for the value of x0, xn and h. After inputting them, it prints the refined value of n & h, and value of each ‘y’ at each intermediate points as shown in the output screen above. At the end, it prints the value of the define integral. To use this source code for other functions, just modify the return(1/(1+pow(x,2))); part in the code.