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

1

How to make a JavaScript program that receives 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++;

   }

}
    
asked by anonymous 25.09.2016 / 03:21

3 answers

1

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

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)) {
	    document.body.innerHTML += i++ + ' ';
    }
}

If you prefer for and more "smart":

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++) {
    document.body.innerHTML += i + '<br>';
}
    
25.09.2016 / 13:48
0

Well considering that num2 is greater than num1 the code to be able to count between them can be as follows:

var num1 = 3;
var num2 = 14;

var numero = num1;

if ((num1 >=0 && num2 >=0) && num1 < num2){
  while (numero <= num2){
    console.log(numero);
    numero++;
  }
}
    
25.09.2016 / 03:36
0

You can compare the numbers and define an order to run while . It would look something like this:

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 might look like this: link

    
25.09.2016 / 08:01