Receive two positive numbers and repeat the interval between them with while?

Asked

Viewed 729 times

1

How to make a Javascript program that takes two positive numbers and repeats the interval between them using while?

var num1 = Number(window.prompt("Entre com primeiro numero"));
var num2 = Number(window.prompt("Entre com segundo numero"));

var numero = 0;

if( num1 >=0 && num2 >=0){

   while (numero>= num1 && numero >=num2){

      document.write (numero+" ");

      numero++;

   }

}
  • What is repeating the interval between them? Repeating what? Is the interval inclusive or exclusive? On both sides?

  • The answers helped you solve the problem?

  • See [tour]. You would help the community by identifying the best solution for you. You can only accept one of them, but you can vote for any question or answer you find useful on the entire site (if you have enough punctuation at the time).

3 answers

1

There is a problem in the condition of while and is not considering that the numbers are not necessarily sorted. You can do so:

var num1 = Number(window.prompt("Entre com primeiro numero"));
var num2 = Number(window.prompt("Entre com segundo numero"));
if (num1 >= 0 && num2 >= 0) {
    var i = Math.min(num1, num2);
    while (i <= Math.max(num1, num2)) console.log(i++);
}

If you prefer the for and more "intelligent":

var num1 = Number(window.prompt("Entre com primeiro numero"));
var num2 = Number(window.prompt("Entre com segundo numero"));
for (var i = Math.min(num1, num2); num1 >= 0 && num2 >= 0 && i <= Math.max(num1, num2); i++) console.log(i);

I put in the Github for future reference.

0

Good considering that num2 is larger than num1 the code to be able to count between them may be the following:

var num1 = 3;
var num2 = 14;

var numero = num1;

if ((num1 >=0 && num2 >=0) && num1 < num2){
  while (numero <= num2){
    console.log(numero);
    numero++;
  }
}
  • but if in this program you need to have 2 entries using prompt as it would be

0

You can compare the numbers and issue an order to run the while. It would be something like that:

var num1 = Number(window.prompt("Entre com primeiro numero"));
var num2 = Number(window.prompt("Entre com segundo numero"));

var start, end;
if (num1 > num2) (start = num2, end = num1);
else if (num1 < num2) (start = num1, end = num2);
else start = end = num1;

var i = start - 1;
while (i++ < end) {
    document.body.innerHTML += i + '<br>';
}

To do the same without using the extremes can be so: https://jsfiddle.net/qr7v3aac/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.