#include <stdio.h>

void main(int argc, char *argv[])
{
  int a, b, n, middle;  /* variables representing interval [a,b] and n */
  int good;
  int cost;     /* number of times for converging */

  if (argc != 4){
    printf("usage: %s a b n\n", argv[0]);
    return;
  }

  good = sscanf(argv[1], "%d", &a) + sscanf(argv[2], "%d", &b)
         + sscanf(argv[3], "%d", &n);

  if (good != 3){
    printf("a, b, n must be integers\n");
    return;
  }

  if (b <= a){   /* b has to be greater than a */
    printf("b's value is not valid.\n");
    return;
  }

  if (n<a || n>b){  /* n should belong to [a,b] */
    printf("n's value is not valid.\n");
    return;
  }

  for (cost =0; a < b; cost++)
    {
      printf("Interval now is: [%d,%d]\n", a, b);

      middle = (a+b)/2;
      if (n <= middle)
	b = middle;
      else
	a = middle+1;
    }

  printf("Finally converged to: [%d,%d]\n", a, b);
  printf("Totally used %d iterations to converge\n", cost);
}



mott$ gcc assign1.c 
mott$ a.out 1 32 15
Interval now is: [1,32]
Interval now is: [1,16]
Interval now is: [9,16]
Interval now is: [13,16]
Interval now is: [15,16]
Finally converged to: [15,15]
Totally used 5 iterations to converge
mott$ a.out 3 16 5
Interval now is: [3,16]
Interval now is: [3,9]
Interval now is: [3,6]
Interval now is: [5,6]
Finally converged to: [5,5]
Totally used 4 iterations to converge
mott$ a.out 1 23 7
Interval now is: [1,23]
Interval now is: [1,12]
Interval now is: [7,12]
Interval now is: [7,9]
Interval now is: [7,8]
Finally converged to: [7,7]
Totally used 5 iterations to converge
