diff --git a/1-js/02-first-steps/12-while-for/1-loop-last-value/solution.md b/1-js/02-first-steps/12-while-for/1-loop-last-value/solution.md old mode 100644 new mode 100755 index 43ee4aad3..beece44a2 --- a/1-js/02-first-steps/12-while-for/1-loop-last-value/solution.md +++ b/1-js/02-first-steps/12-while-for/1-loop-last-value/solution.md @@ -1,4 +1,4 @@ -The answer: `1`. +Resposta: `1`. ```js run let i = 3; @@ -8,18 +8,18 @@ while (i) { } ``` -Every loop iteration decreases `i` by `1`. The check `while(i)` stops the loop when `i = 0`. +Cada iteração do loop decresce `i` em `1`. O teste `while(i)` interrompe o loop quando `i = 0`. -Hence, the steps of the loop form the following sequence ("loop unrolled"): +Portanto, as etapas do loop formam a seguinte sequência ("loop desenrolado"): ```js let i = 3; -alert(i--); // shows 3, decreases i to 2 +alert(i--); // exibe 3, decresce i para 2 -alert(i--) // shows 2, decreases i to 1 +alert(i--) // exibe 2, decresce i para 1 -alert(i--) // shows 1, decreases i to 0 +alert(i--) // exibe 1, decresce i para 0 -// done, while(i) check stops the loop +// pronto, o teste while(i) interrompe o loop ``` diff --git a/1-js/02-first-steps/12-while-for/1-loop-last-value/task.md b/1-js/02-first-steps/12-while-for/1-loop-last-value/task.md old mode 100644 new mode 100755 index 3b847dfa2..dd931937d --- a/1-js/02-first-steps/12-while-for/1-loop-last-value/task.md +++ b/1-js/02-first-steps/12-while-for/1-loop-last-value/task.md @@ -2,9 +2,9 @@ importance: 3 --- -# Last loop value +# Último valor do loop -What is the last value alerted by this code? Why? +Qual é o último valor exibido no alerta por este código? Por quê? ```js let i = 3; diff --git a/1-js/02-first-steps/12-while-for/2-which-value-while/solution.md b/1-js/02-first-steps/12-while-for/2-which-value-while/solution.md old mode 100644 new mode 100755 index 495359876..3a8cc5d6e --- a/1-js/02-first-steps/12-while-for/2-which-value-while/solution.md +++ b/1-js/02-first-steps/12-while-for/2-which-value-while/solution.md @@ -1,30 +1,32 @@ -The task demonstrates how postfix/prefix forms can lead to different results when used in comparisons. +Este exercício demonstra como formas posfixadas/prefixadas podem levar a resultados distintos quando utilizadas em comparações. -1. **From 1 to 4** +1. **De 1 a 4** ```js run let i = 0; while (++i < 5) alert( i ); ``` - The first value is `i = 1`, because `++i` first increments `i` and then returns the new value. So the first comparison is `1 < 5` and the `alert` shows `1`. + O primeiro valor é `i = 1`, pois `++i` primeiro incrementa `i` e em seguida retorna o novo valor. Então, a primeira comparação é `1 < 5` e o `alert` exibe `1`. - Then follow `2, 3, 4…` -- the values show up one after another. The comparison always uses the incremented value, because `++` is before the variable. + Em seguida vêm `2, 3, 4…` -- os valores aparecem um depois do outro. A comparação sempre usa o valor incrementado, pois `++` vem antes da variável. - Finally, `i = 4` is incremented to `5`, the comparison `while(5 < 5)` fails, and the loop stops. So `5` is not shown. -2. **From 1 to 5** + Finalmente, `i = 4` é incrementado a `5`, a comparação `while(5 < 5)` falha, e o loop termina. Assim, `5` não é exibido. + +2. **De 1 a 5** ```js run let i = 0; while (i++ < 5) alert( i ); ``` - The first value is again `i = 1`. The postfix form of `i++` increments `i` and then returns the *old* value, so the comparison `i++ < 5` will use `i = 0` (contrary to `++i < 5`). + O primeiro valor é novamente `i = 1`. A forma posfixada `i++`incrementa `i` e em seguida retorna o valor *antigo*, então a comparação `i++ < 5` utilizará `i = 0` (diferente de `++i < 5`). - But the `alert` call is separate. It's another statement which executes after the increment and the comparison. So it gets the current `i = 1`. + Mas a chamada de `alert` é separada. Ela é uma declaração distinta que executa após o incremento e a comparaçào. Assim, ela recebe o valor atual `i = 1`. - Then follow `2, 3, 4…` + Em seguida, vêm `2, 3, 4…` - Let's stop on `i = 4`. The prefix form `++i` would increment it and use `5` in the comparison. But here we have the postfix form `i++`. So it increments `i` to `5`, but returns the old value. Hence the comparison is actually `while(4 < 5)` -- true, and the control goes on to `alert`. + Vamos parar em `i = 4`. A forma prefixada `++i` iria incrementar e utilizar `5` na comparação. Mas aqui temos a forma posfixada `i++`. Ela incrementa `i` para `5`, mas retorna o valor antigo. Portanto a comparação é, na verdade, `while(4 < 5)` -- verdadeira, e o controle passa para `alert`. - The value `i = 5` is the last one, because on the next step `while(5 < 5)` is false. + O valor `i = 5` é o último, porque na próxima etapa `while(5 < 5)` é falso. + \ No newline at end of file diff --git a/1-js/02-first-steps/12-while-for/2-which-value-while/task.md b/1-js/02-first-steps/12-while-for/2-which-value-while/task.md old mode 100644 new mode 100755 index 298213237..aefb036d3 --- a/1-js/02-first-steps/12-while-for/2-which-value-while/task.md +++ b/1-js/02-first-steps/12-while-for/2-which-value-while/task.md @@ -2,19 +2,19 @@ importance: 4 --- -# Which values does the while loop show? +# Quais valores o loop while retorna? -For every loop iteration, write down which value it outputs and then compare it with the solution. +Para cada iteração dos loops, anote o valor que ele retorna, depois compare com a solução. -Both loops `alert` the same values, or not? +Ambos os loops retornam em `alert` os mesmo valores, ou não? -1. The prefix form `++i`: +1. A forma prefixada `++i`: ```js let i = 0; while (++i < 5) alert( i ); ``` -2. The postfix form `i++` +2. A forma posfixada `i++`: ```js let i = 0; diff --git a/1-js/02-first-steps/12-while-for/3-which-value-for/solution.md b/1-js/02-first-steps/12-while-for/3-which-value-for/solution.md old mode 100644 new mode 100755 index e2e28e75b..d51ed4114 --- a/1-js/02-first-steps/12-while-for/3-which-value-for/solution.md +++ b/1-js/02-first-steps/12-while-for/3-which-value-for/solution.md @@ -1,4 +1,4 @@ -**The answer: from `0` to `4` in both cases.** +**Resposta: de `0` a `4` nos dois casos.** ```js run for (let i = 0; i < 5; ++i) alert( i ); @@ -6,12 +6,12 @@ for (let i = 0; i < 5; ++i) alert( i ); for (let i = 0; i < 5; i++) alert( i ); ``` -That can be easily deducted from the algorithm of `for`: +Isso pode ser facilmente deduzido do algoritmo de `for`: -1. Execute once `i = 0` before everything (begin). -2. Check the condition `i < 5` -3. If `true` -- execute the loop body `alert(i)`, and then `i++` +1. Executar `i = 0` uma vez antes de tudo (início). +2. Verificar a condição `i < 5`. +3. Caso verdadeira (`true`), executar o corpo do loop `alert(i)`, e em seguida `i++`. -The increment `i++` is separated from the condition check (2). That's just another statement. +O incremento `i++` é separado do teste da condição (2). Trata-se de outra declaração. -The value returned by the increment is not used here, so there's no difference between `i++` and `++i`. +O valor retornado pelo incremento não é utilizado aqui, então não há diferença entre `i++` e `++i`. \ No newline at end of file diff --git a/1-js/02-first-steps/12-while-for/3-which-value-for/task.md b/1-js/02-first-steps/12-while-for/3-which-value-for/task.md old mode 100644 new mode 100755 index bfefa63f5..0422670e6 --- a/1-js/02-first-steps/12-while-for/3-which-value-for/task.md +++ b/1-js/02-first-steps/12-while-for/3-which-value-for/task.md @@ -2,18 +2,18 @@ importance: 4 --- -# Which values get shown by the "for" loop? +# Quais valores são mostrados pelo loop "for"? -For each loop write down which values it is going to show. Then compare with the answer. +Pada cada loop, anote quais os valores retornados. Depois, compare com a resposta. -Both loops `alert` same values or not? +Ambos os loops retornam em `alert` os mesmos valores, ou não? -1. The postfix form: +1. A forma posfixada: ```js for (let i = 0; i < 5; i++) alert( i ); ``` -2. The prefix form: +2. A forma prefixada: ```js for (let i = 0; i < 5; ++i) alert( i ); diff --git a/1-js/02-first-steps/12-while-for/4-for-even/solution.md b/1-js/02-first-steps/12-while-for/4-for-even/solution.md old mode 100644 new mode 100755 index e8e66bb47..f7e6e30f8 --- a/1-js/02-first-steps/12-while-for/4-for-even/solution.md +++ b/1-js/02-first-steps/12-while-for/4-for-even/solution.md @@ -8,4 +8,4 @@ for (let i = 2; i <= 10; i++) { } ``` -We use the "modulo" operator `%` to get the remainder and check for the evenness here. +Utilizamos o operador "módulo" `%` aqui para obter o resto e testar se o valor é par. diff --git a/1-js/02-first-steps/12-while-for/4-for-even/task.md b/1-js/02-first-steps/12-while-for/4-for-even/task.md old mode 100644 new mode 100755 index ff34e7e40..5627f1f70 --- a/1-js/02-first-steps/12-while-for/4-for-even/task.md +++ b/1-js/02-first-steps/12-while-for/4-for-even/task.md @@ -2,8 +2,8 @@ importance: 5 --- -# Output even numbers in the loop +# Retornar valores pares no loop -Use the `for` loop to output even numbers from `2` to `10`. +Utilize o loop `for` para retornar números pares de `2` a `10`. [demo] diff --git a/1-js/02-first-steps/12-while-for/5-replace-for-while/solution.md b/1-js/02-first-steps/12-while-for/5-replace-for-while/solution.md old mode 100644 new mode 100755 index 612cf559c..5579686ef --- a/1-js/02-first-steps/12-while-for/5-replace-for-while/solution.md +++ b/1-js/02-first-steps/12-while-for/5-replace-for-while/solution.md @@ -3,7 +3,7 @@ ```js run let i = 0; while (i < 3) { - alert( `number ${i}!` ); + alert( `número ${i}!` ); i++; } ``` diff --git a/1-js/02-first-steps/12-while-for/5-replace-for-while/task.md b/1-js/02-first-steps/12-while-for/5-replace-for-while/task.md old mode 100644 new mode 100755 index 0c69d9c2d..a38929c63 --- a/1-js/02-first-steps/12-while-for/5-replace-for-while/task.md +++ b/1-js/02-first-steps/12-while-for/5-replace-for-while/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Replace "for" with "while" +# Substituir "for" por "while" -Rewrite the code changing the `for` loop to `while` without altering its behavior (the output should stay same). +Reescreva o código, mudando o loop `for` para `while` sem alterar seu comportamento (o resultado deve continuar o mesmo). ```js run for (let i = 0; i < 3; i++) { - alert( `number ${i}!` ); + alert( `número ${i}!` ); } ``` diff --git a/1-js/02-first-steps/12-while-for/6-repeat-until-correct/solution.md b/1-js/02-first-steps/12-while-for/6-repeat-until-correct/solution.md old mode 100644 new mode 100755 index 2e04a78c4..f7ce57442 --- a/1-js/02-first-steps/12-while-for/6-repeat-until-correct/solution.md +++ b/1-js/02-first-steps/12-while-for/6-repeat-until-correct/solution.md @@ -3,13 +3,13 @@ let num; do { - num = prompt("Enter a number greater than 100?", 0); + num = prompt("Digite um número maior que 100:", 0); } while (num <= 100 && num); ``` -The loop `do..while` repeats while both checks are truthy: +O loop `do..while` repete enquanto ambos os testes sejam verdadeiros: -1. The check for `num <= 100` -- that is, the entered value is still not greater than `100`. -2. The check `&& num` is false when `num` is `null` or a empty string. Then the `while` loop stops too. +1. O teste `num <= 100` -- isto é, o valor digitado ainda não é maior que `100`. +2. O teste `&& num` é falso quando `num` é `null` ou um string vazio. Então, o loop `while` também é interrompido. -P.S. If `num` is `null` then `num <= 100` is `true`, so without the 2nd check the loop wouldn't stop if the user clicks CANCEL. Both checks are required. +P.S. Se `num` é `null`, então `num <= 100` é verdadeiro. Por isso, sem o segundo teste, o loop não iria encerrar se o usuário clicasse em "CANCELAR". Ambos os testes são necessários. diff --git a/1-js/02-first-steps/12-while-for/6-repeat-until-correct/task.md b/1-js/02-first-steps/12-while-for/6-repeat-until-correct/task.md old mode 100644 new mode 100755 index 0788ee76e..449e2db5f --- a/1-js/02-first-steps/12-while-for/6-repeat-until-correct/task.md +++ b/1-js/02-first-steps/12-while-for/6-repeat-until-correct/task.md @@ -2,12 +2,12 @@ importance: 5 --- -# Repeat until the input is correct +# Repetir até que o input esteja correto -Write a loop which prompts for a number greater than `100`. If the visitor enters another number -- ask them to input again. +Escreva um loop que peça um número maior que `100`. Se o usuário digitar outro número, peça para digitar novamente. -The loop must ask for a number until either the visitor enters a number greater than `100` or cancels the input/enters an empty line. +O loop deve pedir um número até que o usuário digite um número maior que `100` ou cancele o diálogo/submeta uma linha em branco. -Here we can assume that the visitor only inputs numbers. There's no need to implement a special handling for a non-numeric input in this task. +Aqui podemos assumir que o usuário só digita números. Não é preciso implementar um tratamento especial para inputs não-numéricos neste exercício. [demo] diff --git a/1-js/02-first-steps/12-while-for/7-list-primes/solution.md b/1-js/02-first-steps/12-while-for/7-list-primes/solution.md old mode 100644 new mode 100755 index 9ff0663d7..667669725 --- a/1-js/02-first-steps/12-while-for/7-list-primes/solution.md +++ b/1-js/02-first-steps/12-while-for/7-list-primes/solution.md @@ -1,29 +1,29 @@ -There are many algorithms for this task. +Há muitos algotimos para esta tarefa. -Let's use a nested loop: +Vamos utilizar um loop dentro de outro (isto é, aninhado): ```js -For each i in the interval { - check if i has a divisor from 1..i - if yes => the value is not a prime - if no => the value is a prime, show it +Para cada i no intervalo { + testar se i tem um divisor de 1 a i + se sim => o valor não é um primo + se não => o valor e um primo, mostre-o } ``` -The code using a label: +O código usando um label: ```js run let n = 10; nextPrime: -for (let i = 2; i <= n; i++) { // for each i... +for (let i = 2; i <= n; i++) { // para cada i... - for (let j = 2; j < i; j++) { // look for a divisor.. - if (i % j == 0) continue nextPrime; // not a prime, go next i + for (let j = 2; j < i; j++) { // procurar um divisor.. + if (i % j == 0) continue nextPrime; // não é primo, passar para o próximo i } - alert( i ); // a prime + alert( i ); // é primo } ``` -There's a lot of space to opimize it. For instance, we could look for the divisors from `2` to square root of `i`. But anyway, if we want to be really efficient for large intervals, we need to change the approach and rely on advanced maths and complex algorithms like [Quadratic sieve](https://en.wikipedia.org/wiki/Quadratic_sieve), [General number field sieve](https://en.wikipedia.org/wiki/General_number_field_sieve) etc. +Há muitas maneiras de otimizá-lo. Por exemplo, podemos procurar divisores de `2` até a raiz quadrada de `i`. De qualquer modo, se quisermos ser realmente eficientes para intervalos maiores, precisamos de mudar a abordagem e usar matemática avançada e algoritmos complexos como o [Crivo Quadrático](https://en.wikipedia.org/wiki/Quadratic_sieve), o [Campo de número de peneira geral](https://pt.wikipedia.org/wiki/Campo_de_n%C3%BAmero_de_peneira_geral), etc. \ No newline at end of file diff --git a/1-js/02-first-steps/12-while-for/7-list-primes/task.md b/1-js/02-first-steps/12-while-for/7-list-primes/task.md old mode 100644 new mode 100755 index 6344b9f6f..6e517b8b9 --- a/1-js/02-first-steps/12-while-for/7-list-primes/task.md +++ b/1-js/02-first-steps/12-while-for/7-list-primes/task.md @@ -2,16 +2,17 @@ importance: 3 --- -# Output prime numbers +# Retornar número primos -An integer number greater than `1` is called a [prime](https://en.wikipedia.org/wiki/Prime_number) if it cannot be divided without a remainder by anything except `1` and itself. +Um número inteiro maior que `1` é chamado de [primo](https://pt.wikipedia.org/wiki/Número_primo) se ele não puder ser divido por nenhum outro número exceto por `1` e por si mesmo sem gerar um resto. -In other words, `n > 1` is a prime if it can't be evenly divided by anything except `1` and `n`. -For example, `5` is a prime, because it cannot be divided without a remainder by `2`, `3` and `4`. +Em outras palavras, `n > 1` é um primo se ele não puder ser dividido sem resto por nada além de `1` e `n`. -**Write the code which outputs prime numbers in the interval from `2` to `n`.** +Por exemplo, `5` é um primo, pois não pode ser dividido sem resto por `2`, `3` e `4`. -For `n = 10` the result will be `2,3,5,7`. +**Escreva o código que retorne números primos no intervalo de `2` a `n`.** -P.S. The code should work for any `n`, not be hard-tuned for any fixed value. +Para `n = 10`, o resultado será `2,3,5,7`. + +P.S. O código deve funcionar para qualquer `n`, e não pré-estabelecido para um valor fixo. diff --git a/1-js/02-first-steps/12-while-for/article.md b/1-js/02-first-steps/12-while-for/article.md old mode 100644 new mode 100755 index 6be50597d..584612b33 --- a/1-js/02-first-steps/12-while-for/article.md +++ b/1-js/02-first-steps/12-while-for/article.md @@ -1,54 +1,54 @@ -# Loops: while and for +# Loops: while e for -We often need to repeat actions. +Frequentemente precisamos repetir ações. -For example, outputting goods from a list one after another or just running the same code for each number from 1 to 10. +Por exemplo, retornar itens de uma lista, um atrás do outro, ou apenas executar o mesmo código para cada número de 1 a 10. -*Loops* are a way to repeat the same code multiple times. +*Loops* são uma maneira de repetir o mesmo código múltiplas vezes. -## The "while" loop +## O loop "while" -The `while` loop has the following syntax: +O `while` loop tem a sintaxe seguinte: ```js -while (condition) { - // code - // so-called "loop body" +while (condição) { + // código + // chamado de "loop body" (corpo do loop) } ``` -While the `condition` is `true`, the `code` from the loop body is executed. +Enquanto `condição` for verdadeira, o `código` do corpo do loop é executado. -For instance, the loop below outputs `i` while `i < 3`: +Por exemplo, o loop abaixo retorna `i` enquanto `i < 3`: ```js run let i = 0; -while (i < 3) { // shows 0, then 1, then 2 +while (i < 3) { // retorna 0, depois 1, depois 2 alert( i ); i++; } ``` -A single execution of the loop body is called *an iteration*. The loop in the example above makes three iterations. +Uma única execução do corpo do loop é chamada de *uma iteração*. O loop no exemplo acima realiza três iterações. -If `i++` was missing from the example above, the loop would repeat (in theory) forever. In practice, the browser provides ways to stop such loops, and in server-side JavaScript, we can kill the process. +Se `i++` não estivesse presente no exemplo acima, o loop repetiria (teoricamente) para sempre. Na prática, o navegador nos oferece maneira de interromper tais loops, e em JavaScript server-side, é possível matar o processo. -Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated and converted to a boolean by `while`. +Qualquer expressão ou variável pode ser uma condição para um loop, não apenas comparações: a condição é avaliada e convertida por `while` para um booleano. -For instance, a shorter way to write `while (i != 0)` is `while (i)`: +Por exemplo, uma maneira mais curta de escrever `while (i != 0)` é `while (i)`: ```js run let i = 3; *!* -while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops +while (i) { // quando i se tornar 0, a condição se torna falsa, e o loop para */!* alert( i ); i--; } ``` -````smart header="Brackets are not required for a single-line body" -If the loop body has a single statement, we can omit the brackets `{…}`: +````smart header="Colchetes não são necessários se o corpo possuir só uma linha" +Se o corpo do loop possuir uma única declaração, podemos omitir os colchetes `{...}`: ```js run let i = 3; @@ -58,19 +58,19 @@ while (i) alert(i--); ``` ```` -## The "do..while" loop +## O loop "do..while" -The condition check can be moved *below* the loop body using the `do..while` syntax: +A verificação da condição pode ser movida *abaixo* do corpo do loop utilizando a sintaxe `do..while`: ```js do { - // loop body -} while (condition); + // corpo do loop +} while (condição); ``` -The loop will first execute the body, then check the condition, and, while it's truthy, execute it again and again. +O loop vai executar primeiro o corpo, depois checar a condição e, enquanto ela permanecer verdadeira, executar o corpo novamente. -For example: +Por exemplo: ```js run let i = 0; @@ -80,107 +80,107 @@ do { } while (i < 3); ``` -This form of syntax should only be used when you want the body of the loop to execute **at least once** regardless of the condition being truthy. Usually, the other form is preferred: `while(…) {…}`. +Esta forma de sintaxe deve ser usada apenas quando você deseja que o corpo do loop seja executado **pelo menos uma vez**, independente de a condição ser verdadeira. Geralmente, prefere-se a outra forma: `while(...) {...}`. -## The "for" loop +## O loop "for" -The `for` loop is the most commonly used loop. +O loop `for` é o mais comumente utilizado. -It looks like this: +Ele tem esse formato: ```js -for (begin; condition; step) { - // ... loop body ... +for (início; condição; etapa) { + // ... corpo do loop ... } ``` -Let's learn the meaning of these parts by example. The loop below runs `alert(i)` for `i` from `0` up to (but not including) `3`: +Vamos aprender o que significam cada uma dessas partes através de exemplos. O loop abaixo executa `alert(i)` para `i` de `0` a (não incluso) `3`: ```js run -for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2 +for (let i = 0; i < 3; i++) { // retorna 0, depois 1, depois 2 alert(i); } ``` -Let's examine the `for` statement part-by-part: +Vamos examinar a declaração `for` parte por parte: -| part | | | -|-------|----------|----------------------------------------------------------------------------| -| begin | `i = 0` | Executes once upon entering the loop. | -| condition | `i < 3`| Checked before every loop iteration. If false, the loop stops. | -| step| `i++` | Executes after the body on each iteration but before the condition check. | -| body | `alert(i)`| Runs again and again while the condition is truthy. | +| part | | | +|----------|------------|--------------------------------------------------------------------------------| +| início | `i = 0` | Executado uma vez na entrada do loop. | +| condição | `i < 3` | Verificada a cada iteração do loop. Se falsa, o loop é interrompido. | +| etapa | `i++` | Executado depois do corpo, a cada iteração, mas antes de verificar a condição. | +| corpo | `alert(i)` | Executado repetidamente enquanto a condição for verdadeira. | -The general loop algorithm works like this: +O algoritmo geral do loop funciona assim: ``` -Run begin -→ (if condition → run body and run step) -→ (if condition → run body and run step) -→ (if condition → run body and run step) +Executar início +→ (se condição verdadeira → executar corpo e executar etapa) +→ (se condição verdadeira → executar corpo e executar etapa) +→ (se condição verdadeira → executar corpo e executar etapa) → ... ``` -If you are new to loops, it could help to go back to the example and reproduce how it runs step-by-step on a piece of paper. +Caso loops sejam novos para você, pode ser útil voltar ao exemplo e reproduzir sua execução passo-a-passo em uma folha de papel. -Here's exactly what happens in our case: +No nosso exemplo, o que acontece exatamente é isso: ```js // for (let i = 0; i < 3; i++) alert(i) -// run begin +// executar condição let i = 0 -// if condition → run body and run step +// se condição verdadeira → executar corpo e executar etapa if (i < 3) { alert(i); i++ } -// if condition → run body and run step +// se condição verdadeira → executar corpo e executar etapa if (i < 3) { alert(i); i++ } -// if condition → run body and run step +// se condição verdadeira → executar corpo e executar etapa if (i < 3) { alert(i); i++ } -// ...finish, because now i == 3 +// ...encerrar, pois agora i == 3 ``` -````smart header="Inline variable declaration" -Here, the "counter" variable `i` is declared right in the loop. This is called an "inline" variable declaration. Such variables are visible only inside the loop. +````smart header="Declaração de variável inline" +Aqui, a variável "de contagem" `i` é declarada diretamente no loop. Isso é chamado de declaração de variável "inline". Tais variáveis são visíveis somente no interior do loop. ```js run for (*!*let*/!* i = 0; i < 3; i++) { alert(i); // 0, 1, 2 } -alert(i); // error, no such variable +alert(i); // erro, variável não existente ``` -Instead of defining a variable, we could use an existing one: +Ao invés de definir a variável, podemos utilizar uma já existente: ```js run let i = 0; -for (i = 0; i < 3; i++) { // use an existing variable +for (i = 0; i < 3; i++) { // usando uma variável pré-existente alert(i); // 0, 1, 2 } -alert(i); // 3, visible, because declared outside of the loop +alert(i); // 3, visível, porque declarada fora do loop ``` ```` -### Skipping parts +### Omitindo partes -Any part of `for` can be skipped. +Qualquer parte de `for` pode ser omitida. -For example, we can omit `begin` if we don't need to do anything at the loop start. +Por exemplo, podemos omitir `início` caso não seja necessário fazer nada no início do loop. -Like here: +Como neste exemplo: ```js run -let i = 0; // we have i already declared and assigned +let i = 0; // já temos i declarada e atribuída -for (; i < 3; i++) { // no need for "begin" +for (; i < 3; i++) { // "início" não é necessário alert( i ); // 0, 1, 2 } ``` -We can also remove the `step` part: +Também podemos remover a parte da `etapa`: ```js run let i = 0; @@ -190,32 +190,32 @@ for (; i < 3;) { } ``` -This makes the loop identical to `while (i < 3)`. +Isso torna o loop idêntico a `while (i < 3)`. -We can actually remove everything, creating an infinite loop: +Na verdade, podemos remover tudo, criando um loop infinito: ```js for (;;) { - // repeats without limits + // repete sem limites } ``` -Please note that the two `for` semicolons `;` must be present. Otherwise, there would be a syntax error. +Note que os dois pontos-e-vírgulas `;` dentro do `for` devem estar presentes. Caso contrário, haverá um erro de sintaxe. -## Breaking the loop +## Quebrando o loop -Normally, a loop exits when its condition becomes falsy. +Normalmente, um loop se encerra quando sua condição se torna falsa. -But we can force the exit at any time using the special `break` directive. +Mas podemos forçar a saída a qualquer momento utilizando o comando especial `break`. -For example, the loop below asks the user for a series of numbers, "breaking" when no number is entered: +Por exemplo, o loop abaixo pede ao usuário uma série de números, e "quebra" quando nenhum número é informado: ```js let sum = 0; while (true) { - let value = +prompt("Enter a number", ''); + let value = +prompt("Digite um número", ''); *!* if (!value) break; // (*) @@ -224,35 +224,35 @@ while (true) { sum += value; } -alert( 'Sum: ' + sum ); +alert( 'Soma: ' + sum ); ``` -The `break` directive is activated at the line `(*)` if the user enters an empty line or cancels the input. It stops the loop immediately, passing control to the first line after the loop. Namely, `alert`. +O comando `break` é ativado na linha `(*)` se o usuário deixa a linha em branco ou cancela o diálogo. Ele interrompe o loop imediatamente, passando o controle à primeira linha depois do loop. Neste caso, `alert`. -The combination "infinite loop + `break` as needed" is great for situations when a loop's condition must be checked not in the beginning or end of the loop, but in the middle or even in several places of its body. +A combinação "loop infinito " `break` quando necessário" é ótima para situações onde a condição do loop precisa ser verificada não no início ou no fim do loop, mas no meio, ou até mesmo em vários lugares do corpo do loop. -## Continue to the next iteration [#continue] +## Continue para a próxima iteração [#continue] -The `continue` directive is a "lighter version" of `break`. It doesn't stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows). +O comando `continue` é uma "versão mais light" de `break`. Ele não interrompe o loop como um todo. Ao invés disso, ele interrompe a iteração atual e força o loop a começar uma nova (se a condição permitir). -We can use it if we're done with the current iteration and would like to move on to the next one. +Você pode utilizá-lo caso a iteração atual já não seja útil e você deseje passar para a próxima. -The loop below uses `continue` to output only odd values: +O loop abaixo usa `continue` para exibir apenas valores ímpares: ```js run no-beautify for (let i = 0; i < 10; i++) { - // if true, skip the remaining part of the body + // se verdadeiro, pular o restante do corpo *!*if (i % 2 == 0) continue;*/!* alert(i); // 1, then 3, 5, 7, 9 } ``` -For even values of `i`, the `continue` directive stops executing the body and passes control to the next iteration of `for` (with the next number). So the `alert` is only called for odd values. +Para valores pares de `i`, o comando `continue` interrompe a execução do corpo e passa o controle para a próxima iteração de `for` (com o número seguinte). Então `alert` só é chamado para valores ímpares. -````smart header="The `continue` directive helps decrease nesting" -A loop that shows odd values could look like this: +````smart header="O comando `continue` ajuda a reduzir aninhamento" +Um loop que retorna apenas valores ímpares poderia ter a seguinte forma: ```js for (let i = 0; i < 10; i++) { @@ -264,15 +264,15 @@ for (let i = 0; i < 10; i++) { } ``` -From a technical point of view, this is identical to the example above. Surely, we can just wrap the code in an `if` block instead of using `continue`. +De uma perspectiva técnica, isso é idêntico ao exemplo anterior. Certamente, podemos apenas envolver o código em um bloco `if` ao invés de utilizar `continue`. -But as a side-effect, this created one more level of nesting (the `alert` call inside the curly braces). If the code inside of`if` is longer than a few lines, that may decrease the overall readability. +Mas como efeito colateral, isso criou mais um nível de aninhamento (o `alert` dentro dos colchetes). Se o código dentro de `if` for mais longo do que algumas linhas, isso pode reduzir a legibilidade de forma geral. ```` -````warn header="No `break/continue` to the right side of '?'" -Please note that syntax constructs that are not expressions cannot be used with the ternary operator `?`. In particular, directives such as `break/continue` aren't allowed there. +````warn header="Não utilize `break/continue` do lado direito de '?'" +Note que construções sintáticas que não sejam expressões não podem ser utilizados com o operador ternário `?`. Em particular, comandos como `break/continue` não são permitidos nesta posição. -For example, if we take this code: +Por exemplo, se tomarmos este código: ```js if (i > 5) { @@ -282,104 +282,102 @@ if (i > 5) { } ``` -...and rewrite it using a question mark: - +...e reescrevermos utilizando o ponto de interrogação: ```js no-beautify -(i > 5) ? alert(i) : *!*continue*/!*; // continue isn't allowed here +(i > 5) ? alert(i) : *!*continue*/!*; // continue não é permitido aqui ``` -...it stops working. Code like this will give a syntax error: - +...ele para de funcionar. Códigos como este vão gerar um erro de sintaxe. -This is just another reason not to use the question mark operator `?` instead of `if`. +Esta é apenas mais uma razão para não utilizar o operador ternário `?` no lugar de `if`. ```` ## Labels for break/continue -Sometimes we need to break out from multiple nested loops at once. +Às vezes, precisamos quebrar vários loops aninhados de uma vez só. -For example, in the code below we loop over `i` and `j`, prompting for the coordinates `(i, j)` from `(0,0)` to `(3,3)`: +Por exemplo, no código abaixo nós utilizamos dois loops, com `i` e `j`, dando as coordenadas `(i, j)` de `(0,0)` a `(3,3)`: ```js run no-beautify for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { - let input = prompt(`Value at coords (${i},${j})`, ''); + let input = prompt(`Valor nas coordenadas (${i},${j})`, ''); - // what if we want to exit from here to Done (below)? + // e se quisermos sair daqui diretamente para "Pronto" (abaixo)? } } -alert('Done!'); +alert('Pronto!'); ``` -We need a way to stop the process if the user cancels the input. +Precisamos de uma maneira de interromper o processo caso o usuário cancele o input. -The ordinary `break` after `input` would only break the inner loop. That's not sufficient--labels, come to the rescue! +O `break` comum depois de `input` quebraria apenas o loop interno. Isso não é suficiente--labels, ao resgate! -A *label* is an identifier with a colon before a loop: +Um *label* é um identificador com dois pontos antes de um loop: ```js labelName: for (...) { ... } ``` -The `break ` statement in the loop below breaks out to the label: +A declaração `break ` no loop abaixo quebra o loop designado pelo label: ```js run no-beautify *!*outer:*/!* for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { - let input = prompt(`Value at coords (${i},${j})`, ''); + let input = prompt(`Valor nas coordenadas (${i},${j})`, ''); - // if an empty string or canceled, then break out of both loops + // se retornar um string vazio ou cancelar, quebrar ambos os loops if (!input) *!*break outer*/!*; // (*) - // do something with the value... + // fazer algo com input... } } -alert('Done!'); +alert('Pronto!'); ``` -In the code above, `break outer` looks upwards for the label named `outer` and breaks out of that loop. +No código acima, `break outer` procura acima dele o label chamado `outer` e quebra aquele loop. -So the control goes straight from `(*)` to `alert('Done!')`. +Assim o controle vai direto de `(*)` para `alert('Pronto!')`. -We can also move the label onto a separate line: +Também podemos colocar o label em uma linha separada: ```js no-beautify outer: for (let i = 0; i < 3; i++) { ... } ``` -The `continue` directive can also be used with a label. In this case, code execution jumps to the next iteration of the labeled loop. +O comando `continue` também pode ser utilizado com um label. Nesse caso, a execução do código pula para a próxima iteração do loop nomeado pelo label. -````warn header="Labels are not a \"goto\"" -Labels do not allow us to jump into an arbitrary place in the code. +````warn header="Labels não significam \"ir para\"" +Labels não nos permitem pular para qualquer lugar do código. -For example, it is impossible to do this: +Por exemplo, é impossível fazer isso: ```js -break label; // jumps to label? No. +break label; // pula para label? Não. label: for (...) ``` -A call to `break/continue` is only possible from inside a loop and the label must be somewhere above the directive. +Uma chamada de `break/continue` só é possível de dentro de um loop e o label deve estar em algum lugar acima do comando. ```` -## Summary +## Resumo -We covered 3 types of loops: +Nós cobrimos 3 tipos de loops: -- `while` -- The condition is checked before each iteration. -- `do..while` -- The condition is checked after each iteration. -- `for (;;)` -- The condition is checked before each iteration, additional settings available. +- `while` -- A condição é verificada antes de cada iteração. +- `do..while` -- A condição é verificada após cada iteração. +- `for (;;)` -- A condição é verificada antes de cada iteração, configurações adicionais disponíveis. -To make an "infinite" loop, usually the `while(true)` construct is used. Such a loop, just like any other, can be stopped with the `break` directive. +Para fazer um loop "infinito", geralmente se utiliza a construção `white(true)`. Este loop, como qualquer outro, pode ser interrompido com o comando `break`. -If we don't want to do anything in the current iteration and would like to forward to the next one, we can use the `continue` directive. +Se não quisermos fazer nada na iteração atual e gostaríamos de pular para a próxima iteração, podemos utilizar o comando `continue`. -`break/continue` support labels before the loop. A label is the only way for `break/continue` to escape a nested loop to go to an outer one. +`break/continue` suportam labels antes do loop. Um label é a única maneira de fazer um `break/continue` escapar um loop aninhado e ir para o loop de fora. \ No newline at end of file