The code seems reasonable to me (for someone I think is starting out), although there are some problems:
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 (<
).
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.
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).
A functional approach does not interest you:
let maior = elementos.filter(e=> e > 50)
?– Augusto Vasques