secant method program in C. (WITH OUTPUT IMAGE)

#include<stdio.h>
#include<conio.h>
#include<math.h>


float f(float x)
{return ((x*x)-12);
}


void main()
{int i,flag=0;
float a,b,fx1,fx2,x,x1,fx,x2,ea,es=.01;
FILE *fp;
clrscr();
 fp=fopen("secant-op.txt","w");
 fprintf(fp,"\n x1          f(x1)      x2       f(x2)     x         f(x)      ea  ");


  for(i=0;i<10000;i++)
 {
     if((f(i)*f(i+1))<0)
     { x1=i;
      x2=i+1;
      flag=1;
      break;
     }
  }

    if(flag!=1)
    {
      for(i=0;i>-10000;i--)
      {  if(f(i)*f(i-1)<0)
{ x1=i;
  x2=i-1;
  break;
}
      }
    }


fx1=f(x1);
fx2=f(x2);
x=((x1*fx2)-(x2*fx1))/(fx2-fx1);
fx=f(x);
fprintf(fp,"\n %f  %f  %f %f %f %f ",x1,fx1,x2,fx2,x,fx);

do
{x1=x2;
x2=x;
fx2=f(x2);
fx1=f(x1);

x=((x1*fx2)-(x2*fx1))/(f(x2)-f(x1));

ea=fabs((x-x2)/x)*100;

fprintf(fp,"\n \t \t \t \t \t %f %f %f", x,fx,ea);

}
while(ea>es);
fprintf(fp,"\n your ans is %f",x);
getch();
}




After writing this code in c you will get your output in a file name secant-op  that will be created by program in   bin folder. So u will get blank screen on pressing alt+f9  check output in file.

Comments