#include <iostream>
#include <math.h>

double func(double x)
{ return x*x-2.0;}

double bisection(double xl,double xu)
{
//bisection root finding method
double test;
double xr=0;
double es,ea;
double fxl,fxr;
int maxit=100;
int iter=0;
es=0.00000001;
ea=1.1*es;
while((ea>es)&&(iter<maxit))
{
    xr=(xl+xu)/2.0;
    iter++;
    if(xr!=0)
        { ea=fabs((xu-xl)/(xu+xl))*100.0;}
    fxl= func(xl);
    fxr= func(xr);
    test= fxl*fxr;
    if(test==0.0)      ea=0;
    else if(test<0.0)  xu=xr;
    else              {xl=xr;}
} 
if(iter>=maxit) std::cout <<("Maximum number of iteration is exceeded \n result might not be valid");
return xr;
}

int main()
{  double a,b,r;
   std::cout << " INPUT LOWER LIMIT OF SEARCH AREA a : ";
   std::cin >>a;
   std::cout << " INPUT UPPER LIMIT OF SEARCH AREA b : ";
   std::cin >>b;
   r=bisection(a,b);
   std::cout<<"r="<<r;
   return 0;
}
