Using do/while in Javascript to request 10 numbers from the user

Asked

Viewed 107 times

3

My teacher passed an exercise with the following description:

Make a Javascript program that asks for 10 integers and displays how many numbers are greater than 50 - use loop do while.

I couldn’t solve with the use of do while, so I tried to solve it without using the do while, and was as follows:

    
var elementos = []; 
var maior = [];
var menor = [];
var num = 0;
    
while (num < 12) {
elementos.push(parseInt(prompt("Digite um numero inteiro:")));
num++;
}

for (var i = 0; i < elementos.length; i++) {
if (elementos[i] > 50)
  maior.push(elementos[i]);
else
  menor.push(elementos[i]);
}
    
console.log("Existem " + maior.length + " números que maiores que 50!\n");
console.log("Existem " + menor.length + " números menores que 50!");

I wanted to know if my code is too complex for what she asks, and if it is somehow correct and what can be improved.

  • A functional approach does not interest you: let maior = elementos.filter(e=> e > 50) ?

2 answers

6

If you want only the number of numbers over 50, no matter what they are, so you wouldn’t need to store them in an array. Simply increment the counter when the number is greater than 50:

var i = 0, qtd = 0;
do {
    var n = parseInt(prompt('digite um número: '));
    if (n > 50) {
        qtd++;
    }
    i++;
} while(i < 10);
console.log(`Existem ${n} números maiores que 50`);

See also that I used do/while to read the 10 numbers.

And how the n is only used once, maybe you don’t even need it:

do {
    if (parseInt(prompt('digite um número: ')) > 50) {
        qtd++;
    }
    i++;
} while(i < 10);

What may be improved (but I don’t know if it’s a requirement of the exercise) is to validate whether an integer has even been typed:

var i = 0, qtd = 0;
do {
    var n;
    while(true) {
        n = parseInt(prompt('digite um número: '));
        if (isNaN(n)) alert('digite um número válido');
        else break;
    }
    if (n > 50) {
        qtd++;
    }
    i++;
} while(i < 10);
console.log(`Existem ${n} números maiores que 50`);

When parseInt receives something he does not know how to turn into number (following the algorithm described in the documentation), the return is NaN, and then just use isNaN to check if this was the value returned.


Now, if you want to keep all the numbers (both those that were typed, and those that are larger than 50), then you have to keep the 2 arrays. Only you don’t need one loop to read and another to see who is greater than 50. You can do everything in one loop:

var i = 0;
var todos = [], maiores50 = [];
do {
    var n;
    while(true) {
        n = parseInt(prompt('digite um número: '));
        if (isNaN(n)) alert('digite um número válido');
        else break;
    }
    todos.push(n);
    if (n > 50) {
        maiores50.push(n);
    }
    i++;
} while(i < 10);

console.log(`todos os números: ${todos}`);
console.log(`Existem ${maiores50.length} números maiores que 50: ${maiores50}`);

  • Thank you so much for the comment :). It helped me a lot!

4


The code seems reasonable to me (for someone I think is starting out), although there are some problems:

  1. You’re not asking for 10 numbers, but 12

    It can be observed that in the condition num <= lim (in which num is initiated as 0 and lim is defined as 11), 12 iterations will be made in total, since in the inclusive interval between 0 and 11 there are 12 elements.

    You can fix this by changing the condition to num < 10, for example, in which num still begins as 0. Note that now the range is 0 to 10, exclusive - which account for 10 elements in total. Note that for this purpose, in addition to changing lim, changed the operator of smaller than or equal (<=) for less than (<).

  2. About the message that there are no numbers greater than 50

    Analyzing this part of the code:

    for (var i = 1; i <= elementos.length; i++) {
      if (elementos[i] > 50) {
        maior.push(elements[i]);
      } else if(elementos[i] < 50) {
        console.log("Não existem números maiores que 50!");
      }
    }
    

    The message "There are no numbers bigger than 50!" brings me to the idea that, of the total numbers provided by the user, there is no greater than 50. However, this message is printed to each number provided by the user which is less than 50 - which seems to me a mistake.

  3. Where is the do while?

    The statement is clear and asks that the tie do while be used, but... Where is it?! : P In reality, this loop is (rarely) needed and can always be replaced by a while normal (as you did), but if it is in the statement, the instruction should, in theory, be followed.


Anyway, correcting those points, we would have something like:

const elementos = [];
do {
  elementos.push(parseInt(prompt('Digite um número inteiro:')));
} while (elementos.length < 10); // Enquanto o comprimento da lista for menor que 10, execute o bloco `do`.

const maiores = [];
for (let i = 0; i < elementos.length; i++) {
  const atual = elementos[i];
  if (atual > 50) {
    maiores.push(atual);
  }
}

if (maiores.length > 0) {
  console.log('Existem ' + maiores.length + ' números que são maiores que 50!');
} else {
  // Note que só exibiremos esta mensagem caso nenhum número fornecido ser maior que 50.
  console.log('Não existem números maiores que 50!');
}

It is not an error, but as arrays in Javascript have the property length (which returns the length of the array), it is not necessary to keep a "manual" counter to know how many elements were inserted. Only insert until the quantity of elements meets some stop condition.

Note that no type of validation was done to confirm that the value provided by the user was, in fact, a number. If necessary, you can use functions such as Number.isNaN applied to the result of parseInt.

The above code is quite crude, although ideal for those who are still learning. In the future you may learn about Array.prototype.filter, that can simplify the code even further (mainly making the second loop, the for, implicit).

  • Thank you so much for the comment :). It helped me a lot!

Browser other questions tagged

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