My simple Javascript exercises colection starts from page: Some simple Javascript exercises. In this article I propose more.

Exercise 4
Solve a second order equation

<!DOCTYPE html>
<html><head>
<script>
function equation2degree() {
  var a = document.getElementById("number1").value;
  a=parseFloat(a);
  var b = document.getElementById("number2").value;
  b=parseFloat(b);
  var c = document.getElementById("number3").value;
  c=parseFloat(c);
  var delta = b*b-(4*a*c);
  if (delta < 0)
  {
     document.getElementById("solution").innerHTML = "Impossible";
  }
  else
  {
     var x1=(-b+Math.sqrt(delta))/(2*a);
     var x2=(-b-Math.sqrt(delta))/(2*a);         
     document.getElementById("solution").innerHTML = "x<sub>1</sub>=" + x1 + "&nbsp;&nbsp;x<sub>2</sub>=" + x2;
  }
}
</script>
</head><body>
  <h3>Solve a second order equation in the form ax<sup>2</sup>+bx+c=0</h3>
  <p>Insert the coefficients (integer or real numbers, with negative sign if present)<BR><BR>
  a: <input type="text" id="number1"><BR><BR>
  b: <input type="text" id="number2"><BR><BR>
  c: <input type="text" id="number3"><BR><BR>
  <button onclick="equation2degree()">Solve!</button></p>
  <p>Solution:&nbsp;&nbsp;<span id="solution"></span></p>
</body></html>


Exercise 5

Determine if a year is a leap year.
All years whose number represents them is a multiple of 4, are leap years, except for secular years (ie multiples of 100) if their number is not a multiple of 400.

<!DOCTYPE html>
<html><head>
<script>
function leapYear() {
  var year = parseInt(document.getElementById("year").value);
  var leap = false;
  if (year%100==0)   // is it a secular year?
  {
    if (year%400==0)
    {
      leap = true;
    }
  }
  else   // all other years!
  {
    if (year%4==0)
    {
      leap = true;
    }
  }
 
document.getElementById("print").innerHTML = leap;
}
</script>
</head><body>
  <h3>Tell me a year and I determine if it is a leap year!</h3>
  Gimme the year: <input type="number" id="year">
  <button onclick="leapYear()">Submit</button>
  <BR><p>Answer: <span  id="print"></span></p><BR>
</body></html>

 


Advertising

Advertising

Advertising

We use cookies

We use cookies on our website. Some of them are essential for the operation of the site, while others help us to improve this site and the user experience (tracking cookies). You can decide for yourself whether you want to allow cookies or not. Please note that if you reject them, you may not be able to use all the functionalities of the site.