Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
alvar-o wants to merge13 commits intojavascript-tutorial:master
base:master
Choose a base branch
Loading
fromalvar-o:master
Open
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
13 commits
Select commitHold shift + click to select a range
e4765a4
Translate while-for loops
Sep 4, 2019
f313154
deleting
Sep 4, 2019
b17dba1
Translate while-for loops
Sep 4, 2019
78ae1b7
corrections according to the review
alvar-oOct 21, 2019
cfa3af4
fix typo
alvar-oOct 21, 2019
765fbe0
deleting all work to commit with proper credentials
alvar-oOct 21, 2019
787a0ec
commiting translation with proper credentials
alvar-oOct 21, 2019
1c87f6a
copying original files for reviewers to compare
alvar-oOct 21, 2019
0e8eaef
commiting translation with proper credentials
alvar-oOct 21, 2019
b8d6da2
Translate a word.
odsantosJul 15, 2024
59c82e1
Correct a translation typo
odsantosJul 15, 2024
784e756
Remove duplicate translated word, suggest translation change, and rep…
odsantosJul 19, 2024
e0fccfc
Remove duplicate translated word, suggest translation change, and rep…
odsantosJul 19, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions1-js/02-first-steps/12-while-for/1-loop-last-value/solution.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff 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 loopwhen `i = 0`.
Cada iteração do loop decresce`i`em `1`.O teste `while(i)`interrompe o loopquando `i = 0`.

Hence, the steps of theloopform the following sequence ("loopunrolled"):
Portanto, as etapas doloopformam a seguinte sequência ("loopdesenrolado"):

```js
let i = 3;

alert(i--); //shows 3,decreases ito 2
alert(i--); //exibe 3,decresce ipara 2

alert(i--) //shows 2,decreases ito 1
alert(i--) //exibe 2,decresce ipara 1

alert(i--) //shows 1,decreases ito 0
alert(i--) //exibe 1,decresce ipara 0

//done,while(i)check stops the loop
//pronto, o testewhile(i)interrompe o loop
```
4 changes: 2 additions & 2 deletions1-js/02-first-steps/12-while-for/1-loop-last-value/task.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletions1-js/02-first-steps/12-while-for/2-which-value-while/solution.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff 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 1to 4**
1. **De 1a 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 deletions1-js/02-first-steps/12-while-for/2-which-value-while/task.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,19 +2,19 @@ importance: 4

---

#Which values does the whileloop show?
#Quais valores o loop whileretorna?

For every loop iteration, write down which value it outputs and thencompareit with the solution.
Para cada iteração dos loops, anote o valor que ele retorna, depoiscomparecom a solução.

Bothloops `alert`the same values, or not?
Ambos osloopsretornam 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 deletions1-js/02-first-steps/12-while-for/3-which-value-for/solution.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff 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 theloopbody`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 doloop `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 deletions1-js/02-first-steps/12-while-for/3-which-value-for/task.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff 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 comparewith the answer.
Pada cada loop, anote quais os valores retornados. Depois, comparecom a resposta.

Bothloops `alert`same values or not?
Ambos osloopsretornam 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 deletion1-js/02-first-steps/12-while-for/4-for-even/solution.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletions1-js/02-first-steps/12-while-for/4-for-even/task.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletion1-js/02-first-steps/12-while-for/5-replace-for-while/solution.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletions1-js/02-first-steps/12-while-for/5-replace-for-while/task.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletions1-js/02-first-steps/12-while-for/6-repeat-until-correct/solution.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff 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 emptystring. 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 umstring 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 theloopwouldn'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, oloopnão iria encerrar se o usuário clicasse em "CANCELAR". Ambos os testes são necessários.
8 changes: 4 additions & 4 deletions1-js/02-first-steps/12-while-for/6-repeat-until-correct/task.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,12 +2,12 @@ importance: 5

---

#Repeat until theinputis correct
#Repetir até que oinputesteja correto

Write a loopwhich prompts for a number greater than`100`.If the visitor enters another number -- ask them to input again.
Escreva um loopque peça um número maior que`100`.Se o usuário digitar outro número, peça para digitar novamente.

The loopmust ask for a number until either the visitor enters a number greater than`100`or cancels the input/enters an empty line.
O loopdeve 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 deletions1-js/02-first-steps/12-while-for/7-list-primes/solution.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
There are many algorithms for this task.
Há muitos algotimos para esta tarefa.

Let's use a nestedloop:
Vamos utilizar umloop dentro de outro (isto é, aninhado):

```js
For each iin the interval {
check if i has a divisorfrom 1..i
if yes =>the value is not a prime
if no =>the value is a prime, show it
Para cada ino intervalo {
testar se i tem um divisorde 1 ai
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 deletions1-js/02-first-steps/12-while-for/7-list-primes/task.md
100644 → 100755
View file
Open in desktop
Original file line numberDiff line numberDiff 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

[8]ページ先頭

©2009-2025 Movatter.jp