Skip to content

Loops: while and for #77

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
14 changes: 7 additions & 7 deletions 1-js/02-first-steps/12-while-for/1-loop-last-value/solution.md
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The answer: `1`.
Resposta: `1`.

```js run
let i = 3;
Expand All @@ -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
```
4 changes: 2 additions & 2 deletions 1-js/02-first-steps/12-while-for/1-loop-last-value/task.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
24 changes: 13 additions & 11 deletions 1-js/02-first-steps/12-while-for/2-which-value-while/solution.md
100644 → 100755
Original file line number Diff line number Diff line change
@@ -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.

10 changes: 5 additions & 5 deletions 1-js/02-first-steps/12-while-for/2-which-value-while/task.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 7 additions & 7 deletions 1-js/02-first-steps/12-while-for/3-which-value-for/solution.md
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
**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 );

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`.
10 changes: 5 additions & 5 deletions 1-js/02-first-steps/12-while-for/3-which-value-for/task.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down
2 changes: 1 addition & 1 deletion 1-js/02-first-steps/12-while-for/4-for-even/solution.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -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.
4 changes: 2 additions & 2 deletions 1-js/02-first-steps/12-while-for/4-for-even/task.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -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]
2 changes: 1 addition & 1 deletion 1-js/02-first-steps/12-while-for/5-replace-for-while/solution.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
```js run
let i = 0;
while (i < 3) {
alert( `number ${i}!` );
alert( `número ${i}!` );
i++;
}
```
Expand Down
6 changes: 3 additions & 3 deletions 1-js/02-first-steps/12-while-for/5-replace-for-while/task.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -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}!` );
}
```

10 changes: 5 additions & 5 deletions 1-js/02-first-steps/12-while-for/6-repeat-until-correct/solution.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -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.
8 changes: 4 additions & 4 deletions 1-js/02-first-steps/12-while-for/6-repeat-until-correct/task.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -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]
24 changes: 12 additions & 12 deletions 1-js/02-first-steps/12-while-for/7-list-primes/solution.md
100644 → 100755
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 8 additions & 7 deletions 1-js/02-first-steps/12-while-for/7-list-primes/task.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Loading