-
Notifications
You must be signed in to change notification settings - Fork 111
Loops: while and for #50
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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. | ||
|
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 (begin). | ||
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`. |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,7 +3,7 @@ | |
```js run | ||
let i = 0; | ||
while (i < 3) { | ||
alert( `number ${i}!` ); | ||
alert( `número ${i}!` ); | ||
i++; | ||
} | ||
``` | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 digite digitar novamente. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
|
||
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] |
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): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think we need to add the "nested loop" term here, inside parenthesis. |
||
|
||
```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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
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 mudar a abordagem e nos embasar em matemática avançada e algoritmos complexos como o [Crivo Quadrático](https://en.wikipedia.org/wiki/Quadratic_sieve), o [Crivo do Corpo de Números Geral](https://en.wikipedia.org/wiki/General_number_field_sieve), etc. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Write the verbs on simple present: