You can print the positions as you iterate over them, or save the positions in another array and print them at the end:
// Solicitar 5 números e calcular a média
let soma = 0;
let arrNum = [];
for (let cont = 0; cont < 5; cont++) {
let num = parseInt(prompt("Digite um numero qualquer:"));
arrNum.push(num);
soma += num;
}
let media = soma / arrNum.length;
// imprimir as posições conforme são encontradas
for (let i = 0; i < 5; i++) {
if (arrNum[i] > media) {
document.write('<br>posição: ' + i);
}
}
// ou, guardar as posições em outro array e só imprimir no final
let posicoes = [];
for (let i = 0; i < 5; i++) {
if (arrNum[i] > media) {
posicoes.push(i);
}
}
document.write('<br>posições: ' + posicoes);
Another option (which I particularly find less readable and unnecessarily complicated for a case like this, but there are those who prefer it) is to use reduce
(which generates an array of positions):
// Solicitar 5 números e calcular a média
let soma = 0;
let arrNum = [];
for (let cont = 0; cont < 5; cont++) {
let num = parseInt(prompt("Digite um numero qualquer:"));
arrNum.push(num);
soma += num;
}
let media = soma / arrNum.length;
let posicoes = arrNum.reduce(function(acc, num, index) {
if (num > media) {
acc.push(index);
}
return acc;
}, []);
document.write('<br>posições: ' + posicoes);
And of course, you can also use forEach
to go through the elements (in this case it is equivalent to the first option above: print the positions as found):
// Solicitar 5 números e calcular a média
let soma = 0;
let arrNum = [];
for (let cont = 0; cont < 5; cont++) {
let num = parseInt(prompt("Digite um numero qualquer:"));
arrNum.push(num);
soma += num;
}
let media = soma / arrNum.length;
arrNum.forEach(function(num, index) {
if (num > media) {
document.write('<br>posição: ' + index);
}
});
Thank you all for helping!
– Marcel Roberto Piesigilli
@Marcelrobertopiesigilli If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. Don’t forget that you can also vote in response, if it has found it useful.
– hkotsubo