/*--------------------------------------------------------------------*/
/*  Problem chapter4_29                                               */
/*                                                                    */
/*  This program finds the roots of this function in a                */
/*  user-specified interval:  f(x) = sinc(x)                          */

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

#define PI 3.141593

int main(void)
{
   /*  Declare variables and function prototypes.  */
   int n, k;
   double a, b, step, left, right;
   void check_roots(double left, double right);

   /*  Get user input.  */
   printf("Enter interval limits a, b (a<b): \n");
   scanf("%lf %lf",&a,&b);
   printf("Enter step size: \n");
   scanf("%lf",&step);

   /*  Check subintervals for roots.  */
   n = ceil((b - a)/step);
   for (k=0; k<=n-1; k++)
   {
      left = a + k*step;
      if (k == n-1)
         right = b;
	else
         right = left + step;
	check_roots(left,right);
   }
   check_roots(b,b);

   /*  Exit program.  */
   return 0;
}
/*--------------------------------------------------------------------*/
/*  This function checks a subinterval for a root.                    */

void check_roots(double left, double right)
{
   /*  Declare variables and function prototypes.  */
   double f_left, f_right;
   double sinc(double x);

   /*  Evaluate subinterval endpoints and  */
   /*  test for roots.                     */
   f_left = sinc(left);
   f_right = sinc(right);
   if (fabs(f_left) < 0.1e-04)
      printf("Root detected at %.3f \n",left);
   else
      if (fabs(f_right) < 0.1e-04)
	   ;
      else
	   if (f_left*f_right < 0)
	      printf("Root detected at %.3f \n",
		   (left+right)/2);

   /*  Void return.  */
   return;
}
/*--------------------------------------------------------------------*/
/* This function evaluates a sinc function.                           */

double sinc(double x)
{
   /*  Return function value.  */
   if (fabs(x) < 0.0001)
	return 1;
   else
	return sin(PI*x)/(PI*x);
}
/*--------------------------------------------------------------------*/

