clc
clear all
%asking the user to input the degree of the polynomial. 
x = input('enter degree of your polynomial: ');
%asking the user to input the different polynomial coefficients.
poly = zeros(1,x+1);
for i = 1:x+1
    b(i) = input(['Input value of coefficient multiplyng x^', int2str(i-1), ': ']);
    poly(1,x+2-i) = b(i);
end
%specifying the accuracy
eps=1.0e-6;
%generating a range X of values between  -100 and 100
stp=0.1;
X=-100:stp:100;
%calculating polynomial P(x) for all values of range X
P=polyval(poly,X);

cntr=0;
zrs=[];
ndcs=[];
for i=1:1:length(P)-1
%finding in vector P the indices for which P(x)=0 and the indices at which P(x) sign changes. 
    if (abs(P(i))<eps) 
            cntr=cntr+1;
 %recording the root values and the respective values of indicies
            zrs(cntr)=X(i);
            ndcs(cntr)=i;
        end
        if ((abs(P(i))>eps) & (abs(P(i+1))>eps) & (sign(P(i+1))~=sign(P(i))))
            cntr=cntr+1;
%determining the root value with the help of the bisection method
            a=X(i);
 b=X(i+1);

 c=(a*polyval(poly,b)-b*polyval(poly,a))/(polyval(poly,b)-polyval(poly,a));
 
 ccrs=1e+4;
 while ccrs>=eps

 if (polyval(poly,c)*polyval(poly,a)<0)
     b=c;
 else
     a=c;
 end
 c1=(a*polyval(poly,b)-b*polyval(poly,a))/(polyval(poly,b)-polyval(poly,a));
 ccrs=abs(c1-c);
 c=c1;
end

            
            
            
            
     %recording the root values and the respective values of indicies       
            zrs(cntr)=c;
            ndcs(cntr)=i;
        end; 
    end
%returning in the command window the number of roots, and the roots value sorted in ascending orders.
    if (cntr>0)
    display(['It exists ', int2str(cntr), ' roots in considered interval [-100, 100]']) 
    display(['They are,'])
for i=1:1:cntr
   display(['x=', num2str(zrs(i),6)]) 
end
else
  display(['No real roots to be found in considered interval [-100, 100]'])  
end
if (cntr>1)
mn=P(ndcs(1));
mx=P(ndcs(1));
for i=ndcs(1)+1:1:ndcs(length(ndcs))
    if (P(i)>mx)
        mx=P(i);
    end
    if (P(i)<mn)
        mn=P(i);
    end
end

end  
%plotting the graph of P(x) 
plot(X, P)
grid on
grid minor
xlabel('x-axis', 'FontSize',12,'FontWeight','bold', 'Color', 'r')
ylabel('y-axis','FontSize',12,'FontWeight','bold',  'Color', 'r')
title('Graph of Polynomial','FontSize',16,'FontWeight','bold',  'Color', 'b')
if (cntr==0)
axis([-10 10 -10 10])
elseif (cntr==1)
    mn=polyval(poly,zrs(1)-1.3);
    mx=polyval(poly,zrs(1)+1.3);
    if mn>mx
        tmp=mx;
        mn=mx;
        mx=tmp;
    end
 axis([zrs(1)-2 zrs(1)+2 mn mx])
else
  axis([zrs(1)-2 zrs(cntr)+2 mn-2 mx+2]) 
end
% drawing the axes
xL = xlim;
yL = ylim;
line([0 0], yL, 'Color', 'r');  
line(xL, [0 0], 'Color', 'r');  