title: Riemann Sum, Trapezoidal rule in C
body: <p>I've been trying to write a program that solves the area under a curve in C by using the Trapezoidal rule. The problem is, I think my logic is ok, I've review many times the algorithm and I can't still find the error.</p>
  
  <p>In this was something assigned by my professor and he doesn't want us to use array, that's why you won't see any.</p>
  
  <p>It scans func,a, p, q, err, where func is the function that will be used(function #1 or #2, but I've only done the #1),a is a constant, p is the initial x, q is the final x, and err is the margin of error, I think.</p>
  
  <p>the program will divide the interval and calculate areas until last calculation of Area - total area we just calculates equals less than 10^-err</p>
  
  <p>EDIT:I've made a few changes thanks to LutzL</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;math.h&gt;
  
  double F1(double x,double a){
      double f1=0.0;
      f1=(sqrt(a-pow(x,2)));
      return f1;
  }
  
  int main(){
      double a=0.0,p=0.0,q=0.0,h=0.0,x=0.0,err=0;
      int func=3,n=2;
      double power=0.0,T=0.0;
      double sum=0.0,last=0.0,difference=1.0;
  
      scanf("%d",&amp;func);
  
      while(func!=0){
          n=2;
          scanf("%lf%lf%lf%lf",&amp;a,&amp;p,&amp;q,&amp;err);
          power=pow(10.0,-err);
          h=(q-p)/n;
  
          if(func==1){
              difference=1.0;
              while(difference&gt;=power){
                  h=(q-p)/n;
                  sum=0.0;
                  for(x=p+h;x&lt;=q-h;x++){
                      sum+=(2*F1(x,a));
                  }
                  T=(h/2)*(F1(p,a)+F1(q,a)+sum);
                  if(difference==1.0){
                      difference=T;
                  }else{
                      difference=last-T;
                  }
                  last=T;
                  n++;
                  }
          }
      printf("%.5lf\n",T);
      scanf("%d",&amp;func);
      }
  return 0;
  }
  </code></pre>
  
  <p>The error is when I input 1, 4, -2, 1, 9. It should output 5.05481, but instead, it outputs 4.59808.</p>