Skip to content

Commit f8abfa0

Browse files
authored
Merge pull request #50 from Sjesc/while-for
Loops: while and for
2 parents 7c08e4e + 617f0c4 commit f8abfa0

File tree

15 files changed

+193
-195
lines changed

15 files changed

+193
-195
lines changed
Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
The answer: `1`.
1+
La respuesta: `1`.
22

33
```js run
44
let i = 3;
@@ -8,18 +8,18 @@ while (i) {
88
}
99
```
1010

11-
Every loop iteration decreases `i` by `1`. The check `while(i)` stops the loop when `i = 0`.
11+
Cada iteración del bucle disminuye `i` en `1`. La comprobación `while(i)` detiene el bucle cuando `i = 0`.
1212

13-
Hence, the steps of the loop form the following sequence ("loop unrolled"):
13+
Por consiguiente, los pasos del bucle forman la siguiente secuencia ("bucle desenrollado").
1414

1515
```js
1616
let i = 3;
1717

18-
alert(i--); // shows 3, decreases i to 2
18+
alert(i--); // muestra 3, disminuye i a 2
1919

20-
alert(i--) // shows 2, decreases i to 1
20+
alert(i--) // muestra 2, disminuye i a 1
2121

22-
alert(i--) // shows 1, decreases i to 0
22+
alert(i--) // muestra 1, disminuye i a 0
2323

24-
// done, while(i) check stops the loop
24+
// listo, while(i) comprueba y detiene el bucle
2525
```

1-js/02-first-steps/12-while-for/1-loop-last-value/task.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ importance: 3
22

33
---
44

5-
# Last loop value
5+
# Último valor del bucle
66

7-
What is the last value alerted by this code? Why?
7+
¿Cuál es el último valor alertado/mostrado por este código? ¿Por qué?
88

99
```js
1010
let i = 3;
Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,30 @@
1-
The task demonstrates how postfix/prefix forms can lead to different results when used in comparisons.
1+
La tarea demuestra cómo las formas de sufijo y prefijo pueden llevar a diferentes resultados cuando son usadas en comparaciones.
22

3-
1. **From 1 to 4**
3+
1. **Del 1 al 4**
44

55
```js run
66
let i = 0;
77
while (++i < 5) alert( i );
88
```
99

10-
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`.
10+
El primer valor es `i = 1`, porque `++i` primero incrementa `i` y luego retorna el valor nuevo. Así que la primera comparación es `1 < 5` y el `alert` muestra `1`.
1111

12-
Then follow `2, 3, 4…` -- the values show up one after another. The comparison always uses the incremented value, because `++` is before the variable.
12+
Entonces siguen `2, 3, 4…` -- los valores son mostrados uno tras otro. La comparación siempre usa el valor incrementado, porque `++` está antes de la variable.
1313

14-
Finally, `i = 4` is incremented to `5`, the comparison `while(5 < 5)` fails, and the loop stops. So `5` is not shown.
15-
2. **From 1 to 5**
14+
Finalmente, `i = 4` es incrementada a `5`, la comparación `while(5 < 5)` falla, y el bucle se detiene. Así que `5` no es mostrado.
15+
2. **Del 1 al 5**
1616

1717
```js run
1818
let i = 0;
1919
while (i++ < 5) alert( i );
2020
```
2121

22-
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`).
22+
El primer valor es de nuevo `i = 1`. La forma del sufijo de `i++` incrementa `i` y luego retorna el valor *viejo*, así que la comparación `i++ < 5` usará `i = 0` (contrario a `++i < 5`).
2323

24-
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`.
24+
Pero la llamada a `alert` está separada. Es otra declaración, la cual se ejecuta luego del incremento y la comparación. Así que obtiene el `i = 1` actual.
2525

26-
Then follow `2, 3, 4…`
26+
Luego siguen `2, 3, 4…`
2727

28-
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`.
28+
Detengámonos en `i = 4`. La forma del prefijo `++i` lo incrementaría y usaría `5` en la comparación. Pero aquí tenemos la forma del sufijo `i++`. Así que incrementa `i` a `5`, pero retorna el valor viejo. Por lo tanto, la comparación es en realidad `while(4 < 5)` -- verdadero, y el control sigue a `alert`.
2929

30-
The value `i = 5` is the last one, because on the next step `while(5 < 5)` is false.
30+
El valor `i = 5` es el último, porque el siguiente paso `while(5 < 5)` es falso.

1-js/02-first-steps/12-while-for/2-which-value-while/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,19 @@ importance: 4
22

33
---
44

5-
# Which values does the while loop show?
5+
# ¿Qué valores serán mostrados por el bucle while?
66

7-
For every loop iteration, write down which value it outputs and then compare it with the solution.
7+
Para cada iteración del bucle, escribe qué valor será impreso y luego compáralo con la solución.
88

9-
Both loops `alert` the same values, or not?
9+
Ambos bucles ¿`alertan` los mismos valores?
1010

11-
1. The prefix form `++i`:
11+
1. La forma de prefijo `++i`:
1212

1313
```js
1414
let i = 0;
1515
while (++i < 5) alert( i );
1616
```
17-
2. The postfix form `i++`
17+
2. La forma de sufijo `i++`
1818

1919
```js
2020
let i = 0;
Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1-
**The answer: from `0` to `4` in both cases.**
1+
**La respuesta: de `0 `a `4` en ambos casos.**
22

33
```js run
44
for (let i = 0; i < 5; ++i) alert( i );
55

66
for (let i = 0; i < 5; i++) alert( i );
77
```
88

9-
That can be easily deducted from the algorithm of `for`:
9+
Eso puede ser fácilmente deducido del algoritmo de `for`:
1010

11-
1. Execute once `i = 0` before everything (begin).
12-
2. Check the condition `i < 5`
13-
3. If `true` -- execute the loop body `alert(i)`, and then `i++`
11+
1. Ejecutar `i = 0` una vez antes de todo (comienzo).
12+
2. Comprobar la condición `i < 5`.
13+
3. Si `true` -- ejecutar el cuerpo del bucle `alert(i)` y luego `i++`.
1414

15-
The increment `i++` is separated from the condition check (2). That's just another statement.
15+
El incremento `i++` es separado de la comprobación de la condición (2). Es simplemente otra declaración.
1616

17-
The value returned by the increment is not used here, so there's no difference between `i++` and `++i`.
17+
El valor retornado por el incremento no es usado aquí, así que no hay diferencia entre `i++` y `++i`.

1-js/02-first-steps/12-while-for/3-which-value-for/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@ importance: 4
22

33
---
44

5-
# Which values get shown by the "for" loop?
5+
# ¿Qué valores serán mostrados por el bucle "for"?
66

7-
For each loop write down which values it is going to show. Then compare with the answer.
7+
Para cada bucle, anota qué valores mostrará y luego compara las respuestas.
88

9-
Both loops `alert` same values or not?
9+
Ambos bucles ¿`alertan` los mismos valores?
1010

11-
1. The postfix form:
11+
1. La forma del sufijo:
1212

1313
```js
1414
for (let i = 0; i < 5; i++) alert( i );
1515
```
16-
2. The prefix form:
16+
2. La forma del prefijo:
1717

1818
```js
1919
for (let i = 0; i < 5; ++i) alert( i );

1-js/02-first-steps/12-while-for/4-for-even/solution.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,4 @@ for (let i = 2; i <= 10; i++) {
88
}
99
```
1010

11-
We use the "modulo" operator `%` to get the remainder and check for the evenness here.
11+
Usamos el operador "modulo" `%` para conseguir el resto y comprobar la paridad.

1-js/02-first-steps/12-while-for/4-for-even/task.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ importance: 5
22

33
---
44

5-
# Output even numbers in the loop
5+
# Muestra números pares en el bucle
66

7-
Use the `for` loop to output even numbers from `2` to `10`.
7+
Usa el bucle `for` para mostrar números pares del `2` al `10`.
88

99
[demo]

1-js/02-first-steps/12-while-for/5-replace-for-while/solution.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
```js run
44
let i = 0;
55
while (i < 3) {
6-
alert( `number ${i}!` );
6+
alert( `número ${i}!` );
77
i++;
88
}
99
```

1-js/02-first-steps/12-while-for/5-replace-for-while/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ importance: 5
22

33
---
44

5-
# Replace "for" with "while"
5+
# Reemplaza "for" por "while"
66

7-
Rewrite the code changing the `for` loop to `while` without altering its behavior (the output should stay same).
7+
Reescribe el código cambiando el bucle `for` a `while` sin alterar su comportamiento (la salida debería ser la misma).
88

99
```js run
1010
for (let i = 0; i < 3; i++) {
11-
alert( `number ${i}!` );
11+
alert( `número ${i}!` );
1212
}
1313
```
1414

1-js/02-first-steps/12-while-for/6-repeat-until-correct/solution.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@
33
let num;
44

55
do {
6-
num = prompt("Enter a number greater than 100?", 0);
6+
num = prompt("Ingresa un número mayor a 100", 0);
77
} while (num <= 100 && num);
88
```
99

10-
The loop `do..while` repeats while both checks are truthy:
10+
El bucle `do..while` se repite mientras ambas condiciones sean verdaderas:
1111

12-
1. The check for `num <= 100` -- that is, the entered value is still not greater than `100`.
13-
2. The check `&& num` is false when `num` is `null` or a empty string. Then the `while` loop stops too.
12+
1. La condición `num <= 100` -- eso es, el valor ingresado aún no es mayor que `100`.
13+
2. La condición `&& num` -- es falsa cuando `num` es `null` o una cadena de texto vaciá. Entonces el bucle `while` se detiene.
1414

15-
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.
15+
PD. Si `num` es `null` entonces `num <= 100` es `true`, así que sin la segunda condición el bucle no se detendría si el usuario hace click en CANCELAR. Ambas comprobaciones son requeridas.

1-js/02-first-steps/12-while-for/6-repeat-until-correct/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@ importance: 5
22

33
---
44

5-
# Repeat until the input is correct
5+
# Repite hasta que la entrada sea correcta
66

7-
Write a loop which prompts for a number greater than `100`. If the visitor enters another number -- ask them to input again.
7+
Escribe un bucle que solicite un número mayor que `100`. Si el usuario ingresa otro número -- pídele que ingrese un valor de nuevo.
88

9-
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.
9+
El bucle debe pedir un número hasta que el usuario ingrese un número mayor que `100` o bien cancele la entrada/ingrese una linea vacía.
1010

11-
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.
11+
Aquí podemos asumir que el usuario solo ingresará números. No hay necesidad de implementar un manejo especial para entradas no numéricas en esta tarea.
1212

1313
[demo]
Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,28 @@
1-
There are many algorithms for this task.
1+
Hay muchos algoritmos para esta tarea.
22

3-
Let's use a nested loop:
3+
Usemos un bucle anidado.
44

55
```js
6-
For each i in the interval {
7-
check if i has a divisor from 1..i
8-
if yes => the value is not a prime
9-
if no => the value is a prime, show it
6+
Por cada i en el intervalo {
7+
comprobar si i tiene un divisor en 1..i
8+
si tiene => el valor no es un primo
9+
si no => el valor es un primo, mostrarlo
1010
}
1111
```
12-
13-
The code using a label:
12+
El código usando una etiqueta:
1413

1514
```js run
1615
let n = 10;
1716

1817
nextPrime:
19-
for (let i = 2; i <= n; i++) { // for each i...
18+
for (let i = 2; i <= n; i++) { // por cada i...
2019

21-
for (let j = 2; j < i; j++) { // look for a divisor..
22-
if (i % j == 0) continue nextPrime; // not a prime, go next i
20+
for (let j = 2; j < i; j++) { // buscar un divisor..
21+
if (i % j == 0) continue nextPrime; // no es primo, ir al próximo i
2322
}
2423

25-
alert( i ); // a prime
24+
alert( i ); // primo
2625
}
2726
```
2827

29-
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.
28+
Hay mucho lugar para la mejora. Por ejemplo, podríamos buscar por divisores desde `2` hasta la raíz cuadrada de `i`. Pero de todas formas, si queremos ser realmente eficientes para intervalos grandes, necesitamos cambiar el enfoque y confiar en matemáticas avanzadas y algoritmos complejos como [Criba cuadrática](https://es.wikipedia.org/wiki/Criba_cuadr%C3%A1tica), [Criba general del cuerpo de números](https://es.wikipedia.org/wiki/Criba_general_del_cuerpo_de_n%C3%BAmeros) etc.

1-js/02-first-steps/12-while-for/7-list-primes/task.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@ importance: 3
22

33
---
44

5-
# Output prime numbers
5+
# Muestra números primos
66

7-
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.
7+
Un número entero mayor que `1` es llamado [primo](https://es.wikipedia.org/wiki/N%C3%BAmero_primo) si no puede ser dividido sin un resto por ningún número excepto `1` y él mismo.
88

9-
In other words, `n > 1` is a prime if it can't be evenly divided by anything except `1` and `n`.
9+
En otras palabras, `n > 1` es un primo si no puede ser divido exactamente por ningún número excepto `1` y `n`.
1010

11-
For example, `5` is a prime, because it cannot be divided without a remainder by `2`, `3` and `4`.
11+
Por ejemplo, `5` es un primo, porque no puede ser divido exactamente por `2`, `3` y `4`.
1212

13-
**Write the code which outputs prime numbers in the interval from `2` to `n`.**
13+
**Escribe el código que muestre números primos en el intervalo de `2` a `n`.**
1414

15-
For `n = 10` the result will be `2,3,5,7`.
15+
Para `n = 10` el resultado será `2, 3, 5, 7`.
1616

17-
P.S. The code should work for any `n`, not be hard-tuned for any fixed value.
17+
PD. El código debería funcionar para cualquier `n`, no debe estar programado para valores fijos.

0 commit comments

Comments
 (0)