Program 2
Program 2
#include<stdio.h>
#include<math.h>
void main()
{
int n,i,flag=0;
float fa,fb,a,b;
float function(float);
void bisect(float,float,int);
do
{
printf("\n Enter the limits a & b:");
scanf("%f%f",&a,&b);
fa=function(a);
fb=function(b);
if((fa*fb)<0)
flag=1;
else
printf("\n INVALID INPUT!Re-enter the values:");
}while(flag= =0);
printf("\n Enter the number iterations:");
scanf("%d",&n);
printf("\n ----------------------------------------------------------------");
printf("\n ITERATIONS\t a\t b\t c\t f(a)\t f(b)\t f(c)\n");
printf("\n ----------------------------------------------------------------");
bisect(a,b,n);
}
/* FUNCTION BISECTION */
void bisect(float a,float b,int n)
{
int i;
float c,fc,fa,fb;
float function(float);
fa=function(a);
fb=function(b);
for(i=0;i<n;i++)
{
c=(a+b)/2.0;
fc=function(c);
printf("\n %d) \t%2.4f\t%2.4f\t%2.4f",i+1,a,b,c);
printf("\t%2.4f\t%2.4f\t%2.4f",fa,fb,fc);
printf("\n");
if((fa*fc)>0)
a=c,fa=fc;
if((fb*fc)>0)
b=c,fb=fc;
}
printf("\n ---------------------------------------------------------------");
printf("\n\n THE ROOT IS:%f",c);
}
float function(float x)
{
float r;
r=x*x*x-4*x-9;
return(r);
}
-------------------------------------------------------------------------------------------------------------
ITERATIONS a b c f(a) f(b) f(c)
------------------------------------------------------------------------------------------------------------
1) 2.0000 3.0000 2.5000 -9.0000 6.0000 -3.3750
-----------------------------------------------------------------------------------------------------------