Skip to main content

C program for Trapezoidal Rule

C Code for Trapezoidal Rule
#include <stdio.h>
#include <conio.h>
#include <math.h>
float f(float x)
{
  return (exp(x)); //f(x)=exp(x);
}

void main()
{
  float a,b,h,x,sum=0;
  int n;
  printf("Enter a and b: ");
  scanf("%f%f",&a,&b);
  printf("Here, n=1 for Trapezoidal rule");  printf("\nn>1 for Composite Trapezoidal rule\n");
  printf("So, Enter n: ");
  scanf("%d",&n);
  h=(b-a)/n;
  for(x=a;x<=b;x=x+h)
  {
    if(x==a)
      sum=sum+f(x);
    else if(x==b)
      sum=sum+f(x);
    else
      sum=sum+2*f(x);
  }
  sum=h/2*sum;
  printf("\nI=%f",sum);
  getch();
}

Comments

Popular posts from this blog