Ciclos

Ahora bien, ya sabemos procedimientos funciones, variables y repeticiones simples.

Pero, en la programación estructurada también existen una serie de técnicas para crear ciclos, es decir vueltas loops y debemso ser capaces de manejar (contar) en nuestro programa, cada una de esas repeticiones.

De esa forma tenemos mas variedad de opciones para programar nuestros algoritmos, y ya o dependemos de una lsta unidireccional de instrucciones...porque podremos hacer repeticiones y cortes en las repeticiones en partes de una secuencia.


Los Ciclos o Loops)

Un Bucle o Ciclo, es una parte del programa (o una función) que se repite varias veces.

El número de veces que se repite el ciclo se determina como un valor dado por (x) o hasta que se cumplan ciertas condiciones o si no tiene valor, puede ser que se repita infinitamente.


Logo tiene varias funciones para generar Bucles/Ciclos.



REPEAT x (Ciclos simples)


REPEAT llama a la función de repetir (Ciclar) y el número que escribamos en "x", establece el número de veces que se repite el ciclo.

Si omite poner una valor a "x" (es decir en vez de x no escribe nada), la función se reiterará por siempre (de forma infinita), y en la práctica, por lo general, la computadora se apagará cuandos de colapse la memoria o hará que el programa no funciones.



Ejemplo:

HOME CLEARSCREEN SHOWTURTLE

REPEAT 16 [ FORWARD 100 RIGHT 45 ]

HIDETURTLE


Si se fija en éste código las instruciones: "FORWARD 100 RIGHT 45" que están entre corchetes cuadrados, se repetirán 16 veces y luego se detiene el ciclo automáticamente, para proseguir nuevamente siguiendo las órdenes Logo una por una como siempre (si las hay). -Aquñi ocultar tortuga se ejecuta-



Pero en éste ejemplo, en cambio:


HOME CLEARSCREEN SHOWTURTLE

REPEAT [ FORWARD 100 RIGHT 45 ]

HIDETURTLE


Como no especificamos cuantas veces debe repetir, el programa repetirá por siempre el mismo loop (Ciclo infinito) y no leerá ninguna otra órden que aparezca debajo...

Porque nunca se detendrá. - Así que jamas se ejecutará OCULTARTORTUGA.


(ANTIGUAMENTE SOLÍA COLAPSAR LA MEMORIA DE LAS MÁQUINAS, así que no se utilizaba, pero ahora se puede utilizar, generalmente para realizar animaciones de ciclo infinito.

Por ejemplo, para programar una animación que muestre la Tierra girando al rededor del Sol.)


  • Se puede también poner ciclos dentrod e ciclos.

Ejemplo:

HOME CLEARSCREEN SHOWTURTLE

REPEAT 4 [ FORWARD 50 RIGHT 90 FORWARD 100 REPEAT 2 [ FORWARD 50 RIGHT 90 ] ]

HIDETURTLE




Veamos otros ciclos


FOR … IN (Ciclo Para)

This function retrieves data one by one from a list of data. The loop ends when there are no more elements in the list.

FOR :x IN [10, 50, 80, 120, 180] [

FORWARD :x

LEFT 90

]

will add data from the list [10, 50, 80, 120, 180] one at the time to the variable :x and execute commands in turn. First command will then be FORWARD 10 LEFT 90. Next will be FORWARD 50 LEFT 90 and so forth until the loop is ended with FORWARD 180 LEFT 90.

Also text strings are in this case a list so it is possible to get data from a string.

FOR x IN "This is a text string" [

LABEL x

FORWARD 10

]

will print the text letter by letter on the screen.

To make a loop that runs from 0 to 20, enter FOR :n IN RANGE 20 [action]

This is the same as writing FOR n=0 to 19 in other programming languages.



REPCOUNT (contador la repeticiones o "contador")

Perhaps in the example above you prefer to use the value of the counter instead of values ​​from the list. You must then replace :n with REPCOUNT. REPCOUNT returns the value of the element counter and the function will repeat as many times as there are elements in the list.

REPCOUNT can be used in the loops REPEAT, FOR and WHILE.



WHILE (Ciclo Mientras)

Like FOR, but loops until the condition is met.

WHILE REPCOUNT <= 10 [

FORWARD 45

RIGHT 36

]

The loop will be executed as long as repcount is less than or equal to 10. Repcount counts from 1, not from 0 as usual in other programming languages. Therefore the loop will be executed 10 times and render a polygon with 10 sides.


BREAK (Corte, interrupción)

This is not a procedure, but a command that terminates the loop. It is always used together with a condition (see below).

Example:

REPEAT [

BACK 50 LEFT 45

IF REPCOUNT = 20 [ BREAK ]

]

In this example, the procedure will be repeated until REPCOUNT equals 20. Thus actually the same as REPEAT 20.

Return from the procedure. Used together with a condition.


CONTINUE (Continuar)

This will skip the command that follows CONTINUE and jump to the line after the command. An example:

REPEAT 8 [

BACK 60 RIGHT 45

IF REPCOUNT % 2 = 0 [ CONTINUE ]

SQUARE 15

]

The term REPCOUNT % 2 = 0 is TRUE if REPCOUNT divided with 2 gives remainder 0. (Refer to the chapter on mathematics). If repcount is an even number the expression inside the brackets will be performed. In this case this is CONTINUE, which means that the procedure is performed from the start, without bothering about the rest of the commands in the procedure. The example will draw a polygon with 8 sides with a square in every second corner. See image at right.


STOP (Detener)

As BREAK but returns from a procedure.

Example:

It is meaningless to try to render a polygon with less than 3 sides. So if the call asks for a polygon with less than three sides, the function below refuses to render a figure:

TO polygon :edges :size :color :line

IF :edges < 3 [ STOP ] ; return if fewer than 3 sides, else continue

PENCOLOR :color

PENWIDTH :line

REPEAT :edges [

FORWARD :size

LEFT 360 / :edges

]

END



PAUSE (Pausa)

PAUSE 500 ; Wait for 0,5 second.

Is, not unexpectedly, used for making a pause in the program. The time is measured in milliseconds.