Jay
Jay

Reputation: 23

Multiplication table in JavaScript - 2 tables

I'm, starting to learn javascript and I have a problem with this code. The code asks for two numbers (the first must be lower than the second) and then it shows the multiplication from the first to the second number. If you type 5 and 7, it shows the multiplication of 5, 6 and 7.

The problem comes when the second number is typed is 10 (except if you type 1 and 10, it shows all). If I type 2 and 10 it shows nothing.

Thanks in advance.

<script>
function multiply() {
do {
  do {
    var i1 = prompt("Type first number from 1 to 10", "");
  } while (i1 < 1 || i1 > 10);

  do {
    var i2 = prompt("Type second number from 1 to 10 (number must be higher than the first one", "");
  } while (i2 < 1 || i2 > 10);

  var check = i2 - i1;

  if (check >= 0) {
    for (var i = i1; i <= i2 ; i++) {
        for (var j = 1; j <= 10; j++) {
      document.write("<br>" + i + " x " + j + " = " +  i * j);
        }
    document.write("<p>" );
    }
  } else {
    alert("First number is higher than the second, PLease try again.")
    }

} while (check < 0)
} 
</script>

Upvotes: 2

Views: 460

Answers (1)

wayneOS
wayneOS

Reputation: 1425

The return-value of prompt () is a string. So you need to parseInt() to get integers.

do {
  do {
    var i1 = parseInt (prompt("Type first number from 1 to 10", ""));
  } while (i1 < 1 || i1 > 10);

  do {
    var i2 = parseInt (prompt("Type second number from 1 to 10 (number must be higher than the first one", ""));
  } while (i2 < 1 || i2 > 10);

  var check = i2 - i1;

  if (check >= 0) {
    for (var i = i1; i <= i2 ; i++) {
        for (var j = 1; j <= 10; j++) {
      document.write("<br>" + i + " x " + j + " = " +  i * j);
        }
    document.write("<p>" );
    }
  } else {
    alert("First number is higher than the second, PLease try again.")
    }

} while (check < 0)

Upvotes: 3

Related Questions