Book Site Banner
Companion site for the book (ISBN:9781032568997)
  

Javascript for Chicken and Rabbits Problem

Try the Javascript Program



The Javascript Source Code


function CRprog()
{  var r, c, H, L;
   H = parseInt(prompt("Please enter head count"));
   if ( ! Number.isInteger(H) ) return 0; 
   L = parseInt(prompt("Please enter leg count"));
   if ( ! Number.isInteger(L) ) return 0; 
   alert("heads = "+ H +" and legs = "+ L);
   if ( valid(H,L) ) 
   {  r = L/2 - H;  c = H - r;
      alert("Anser: "+ r +" Rabbits and "+
            c +" Chickens."); 
   }
   else
   {  alert("Invalid Input! You may try again."); 
   }
   if ( confirm("Try Again?") ) { CRprog() }; 
}

function valid(H, L)
{  return 
   ( Number.isInteger(H) && Number.isInteger(L)
     && H >= 0 && L >=0 && (L % 2 == 0) &&
     L >= 2*H && L <= 4*H );
}