A for
consists of 3 blocks: an initialization, a condition indicating when to end loop repetition and a processing that must happen every time a repetition step ends.
The first is quiet playing using O while
because simply initialize before the loop. The only drawback may be the scope of the variable is beyond the loop block as it occurs in the for
depending on how you declare.
The second part is what will remain in while
since the only function of the control is the condition.
The third part to be modified may be problematic in some cases where it has a continue
because the execution would change and the result would be different if not taking certain precautions, but it is not the case of your code, so I put the incrementer inside the loop as last command, it would be like this:
var ordinais = ['primeira', 'segunda', 'terceira', 'quarta'];
var media = 0;
var i = 0;
while (i < ordinais.length) {
var nota = prompt("Informe a " + ordinais[i] + " nota: ");
if (nota === "" || !nota) nota = 0;
media += parseFloat(nota);
i++;
}
media /= ordinais.length;
if (media >= 7) document.write("Aprovado");
else if (media <= 5) document.write("Reprovado");
else document.write("Recuperação");
I put in the Github for future reference.
I wouldn’t do that in this case, even if it doesn’t change anything relevant. O for
seems the perfect solution.
I fixed some code errors. I changed the last condition because I had notes that did nothing. It must still be there because the recovery track is very strange, but without enunciation I can not correct it (I had another error in the condition, but except it no longer has). There is still possibility of invalid typing giving issue on execution.
Is there a reason for this? The
for
is more appropriate in this case (since it allows you to maintain the state of the iteration position in the syntactic construction itself). Moreover, because it has passed3
in the second argument ofparseFloat
? This function only accepts an argument.– Luiz Felipe