Basic programming course: Lesson #5 Control structures. Part 2. Cycles. [ESP-ENG]

in devwithseven •  12 days ago 

Lesson #5.jpg

Creado con canva

ESP

Untitled design.png


Estructuras repetitivas


Ya vimos cómo podemos hacer a nuestros programas tomar decisiones por nosotros permitiéndonos a seguir un camino u otro después del análisis de algunos datos. Ahora vamos a aprender a utilizar una de las estructuras de control más importantes de la programación y es que seguramente ya muchos lo habrán notado, pero muchas de las tareas que programamos son en ser bastante repetitivas, es decir, la misma tarea pero con un pequeñitas modificaciones, por lo que el día de hoy conoceremos las estructuras repetitivas que como su nombre lo indica son estructuras que te ayudarán a repetir una parte del código de acuerdo a una condición, mientras la condición sea verdadera la estructura seguirá repitiendo la instrucción, y una vez la condición se vuelve a falsa la estructura repetitiva finalizará y el programa continuará su ciclo habitual.


Contadores y acumuladores


Antes de comenzar a explicarlo ciclos me gustaría aclarar estos dos conceptos que utilizaremos bastante mientras estemos repitiendo código con los ciclos. Los contadores y acumuladores técnicamente son simplemente variables que utilizaremos para contar o acumular valores como su nombre lo indica.

Es decir, con un contador podríamos contar valga la redundancia la cantidad de veces que un ciclo ha repetido el código, y con un acumulador podríamos sumar en cada repetición del ciclo un valor que el usuario nos proporcione.

La diferencia entre cada uno, es que el contador va incrementando su valor de uno en uno como si estuviera contando normalmente y el acumulador puede incrementar su valor de forma variable dependiendo de las necesidades del programa. Esto lo veremos más claramente en los ejemplos.


Ciclos


  • Mientras: para usar el ciclo mientras utilizaremos la palabra “Mientras” seguida de la condición que se debe cumplir para que el ciclo se ejecute, y finalmente la palabra “Hacer”. Justo al final de la estructura colocaremos la palabra “FinMientras”. Todo lo que esté dentro de esta estructura se repetirá acorde a la condición que hayamos establecido, por ejemplo vamos a realizar este ejercicio definiendo dos variables enteras, un contador y un acumulador. Ambas variables deben recibir un valor inicial, en el caso del contador generalmente se inicia en 1 porque empezará a contar desde allí, y el acumulador en 0 porque aún no ha recibido ningún valor para empezar a sumar.
Definir c, a Como Entero;
    c = 1;
    a = 0;

Vamos a hacer un ciclo que se ejecute 10 veces entonces a la condición del ciclo mientras va a ser que mientras el contador sea menor o igual a 10 entonces la condición se seguirá repitiendo.

Mientras c <=10 Hacer
        // Todo lo que se repetirá aca
    FinMientras

Ahora dentro del ciclo lo que haremos será simplemente imprimir un mensaje con los valores de acumulador y contador. En este caso también imprimiré una línea para separar un poco la información que se imprime en cada ciclo.

Imprimir  "Cont: " c;
        Imprimir "Acum: " a;
        Imprimir "-------------------------------------";

Ahora, justo al final del ciclo debemos modificar los valores de las variables, si no hacemos esto crearemos un ciclo infinito y nuestra computadora podría no resistirlo ya que será mucha información que estará ejecutando infinitamente, por lo que tenemos que tener cuidado al crear los ciclos y que la lógica sea correcta para evitar estas situaciones. Lo que tenemos que hacer es simplemente sumarle 1 al contador y sumarle lo que haga falta a acumulador, en este caso simplemente iré sumándole el valor del contador cada vez. Esto se logra así:

c = c + 1;
a = a + c;

Lo que estamos haciendo es decir que c es igual a c +1, si analizamos un poco el programa veremos que c empezó con un valor inicial de 1, en la primera vuelta del ciclo sumaremos a c con 1, lo que sería igual a 1+1. El resultado de esta operación es 2, entonces en la siguiente vuelta c ya tiene un valor de 2. Y volvemos a repetir esta operación, c+1, sabiendo que c ahora tiene un valor de dos entonces la operación sería 2+1, lo que da como resultado 3. Y en la siguiente vuelta volvemos a repetir esto cada vez y así vamos incrementando el valor de c con cada vuelta del ciclo. Una vez c tenga un valor de 11 el ciclo se detendrá ya que la condición ahora será falsa.

De la misma forma trabajamos con los acumuladores, en este caso simplemente fui acumulando el valor de c. El código quedaría de la siguiente manera:

Algoritmo cycles
    Definir c, a Como Entero;
    c = 1;
    a = 0;
    Mientras c <=10 Hacer
        Imprimir  "Cont: " c;
        Imprimir "Acum: " a;
        Imprimir "-------------------------------------";
        c = c + 1;
        a = a + c;
    FinMientras
FinAlgoritmo

Si ejecutamos este código podremos ver lo siguiente:

Captura de pantalla 2024-10-06 a la(s) 11.12.29 a. m..png

  • Para: el ciclo para es bastante parecido al ciclo anterior, sólo que en este caso el mismo ciclo tendrá el contador declarado de forma implícita y no tendremos que preocuparnos por manejarlo, generalmente el contador del ciclo para es una variable llamada i, y no es necesario declararla ya que dentro del mismo ciclo se hace automáticamente. Usar este ciclo es muy sencillo, simplemente pondremos la palabra “Para” seguida del nombre de la variable contador, en este caso como ya lo mencioné la convención es utilizar la letra i. Después utilizaremos la palabra “desde” seguida de el número donde empezará el ciclo, es decir, el valor inicial de i después la palabra “hasta” seguida del número hasta donde se ejecutará el ciclo.

Para mostrarte el ejemplo simplemente haremos un ciclo que se ejecute cinco veces por lo que quedaría de la siguiente manera:

Para i desde 1 hasta 5 Hacer
        Imprimir i; 
    FinPara 

Acá se simplemente estamos ejecutando el ciclo cinco veces y estamos mostrando la variable i para que puedan comprobar su valor en cada vuelta del ciclo. Si ejecutamos este código tendremos lo siguiente:

Captura de pantalla 2024-10-06 a la(s) 11.56.19 a. m..png

  • Hacer-Mientras: técnicamente este ciclo es lo mismo que el ciclo mientras, sólo que este anterior debe cumplirse la condición para que puedas ejecutarse todo el ciclo, sin embargo, el ciclo hacer-mientras se ejecutará una vez y después evaluará la condición que determinará si se seguirá ejecutando o si se detendrá inmediatamente. Esto podemos verlo de forma más clara con un ejemplo, supongamos que queremos pedir la edad de un usuario, pero esta no puede ser menor a 18, entonces podemos hacer un ciclo que se mantenga ejecutándose infinitamente mientras la edad proporcionada no sea mayor o igual que 18, vamos a probarlo.

Primero vamos a declarar las variables, en este caso un nombre y una edad. Después vamos a pedir el nombre como normalmente lo haríamos.

Definir edad Como Entero;
    Definir nombre Como Caracter;
    
    Imprimir "Ingresa tu nombre:";
    Leer nombre;

Acá comenzaremos el ciclo, pondremos la palabra “Repetir” y cerraremos esta estructura con las palabras “Hasta Que” seguida de la condición a evaluar. Todo lo que esté dentro de esa estructura se repetirá hasta que la condición sea verdadera tal como su nombre nos lo sugiere.

Vamos a solicitar la edad del usuario normalmente. Yo puse un pequeño condicional al final del ciclo que evalúa si la edad es menor a 18, en este caso le muestra al usuario un mensaje que le indica que debe intentarlo nuevamente ya que debe ser mayor de edad.

Repetir
        Imprimir "Ingresa tu edad:";
        Leer edad;
        
        Si (edad < 18) Entonces
            Imprimir "Debes ser mayor de edad, intenta nuevamente.";
        FinSi
    Hasta Que edad >= 18

Esta instrucción funciona de la siguiente manera: el usuario va a ingresar su edad, si su edad es menor a 18 entonces se mostrará el mensaje de qué debe intentarlo nuevamente, como la instrucción no cumple con la condición del hasta que entonces se volverá a repetir y volverá a preguntar la edad de el usuario, esto lo hará hasta que el programa reciba un valor mayor o igual que 18.

Vamos a ver la ejecución:

Captura de pantalla 2024-10-06 a la(s) 12.17.59 p. m..png


Ejemplo


Vamos a crear un programa que pregunte al usuario cuántos nombres desea ingresar, y a partir de allí ejecutar un ciclo para pedir cada uno de los nombres, después al final del ejercicio se mostrará la lista con todos los nombres.

Para ello tendremos que crear tres variables, una para crear la lista de nombres que será un acumulador de texto, una variable para leer cada nombre, y una variable entera para preguntar cuántos nombres desea el usuario ingresar.

Inicializaremos la variable acumuladora de nombres como una cadena de texto vacía, para ello pondremos las dos " sin nada entre ellas. Después preguntaremos cuántos nombres se desean ingresar.

Definir nombres, nombre Como Caracter;
    Definir n Como Entero;
    
    nombres = "";
    
    Imprimir "Cuantos nombres desea leer?";
    Leer n;

Después haremos un ciclo Para que irá de 1 hasta n que es la variable donde almacenaremos la cantidad de nombres que desea ingresar el usuario. Dentro del ciclo comenzaremos a leer todos los nombres y acumularlos en la variable nombres. Decimos que nombres es igual a nombres, le agregamos un espacio y la variable nombre que recién acabamos de leer en esa vuelta del ciclo. Así todos los nombres se irán almacenando en esta cadena que imprimiremos justo al finalizar el ciclo.

Para i desde 1 hasta n Hacer
        Imprimir "Introduce un nombre";
        Leer nombre;
        
        nombres = nombres + " " + nombre;
    FinPara
    
    Imprimir "Lista: " nombres;

Éste código ejecutado se vería así:

Captura de pantalla 2024-10-06 a la(s) 12.57.51 p. m..png


Tarea


  • Explique los ciclos de forma detallada. Que son y como se usan? Cual es la diferencia del ciclo Mientras y Hacer-Mientras?
  • Investiga como se utiliza la estructura Segun-caso y danos un ejemplo.
  • Explica lo que hace el siguiente código:
Algoritmo seguncaso
    Definir  op, n, ns, a Como Entero;
    Definir exit Como Logico;
    
    exit = Falso;
    a=0;
    
    Repetir 
        Imprimir  "Selecciona una opcion:";
        Imprimir  "1. Sumar numeros.";
        Imprimir  "2. Mostrar resultados."
        Imprimir  "3. Finalizar programa."; 
        Leer op;
        
        Segun op Hacer
            caso 1:
                Imprimir "Cuantos numeros desea sumar?";
                Leer n; 
                Para i desde 1 hasta n Hacer
                    Imprimir "Ingresa un numero: ";
                    Leer ns; 
                    a = a + ns;
                FinPara
                Imprimir "Completado! Presione cualquier tecla para continuar.";
                Esperar Tecla;
                Limpiar Pantalla;
            caso 2:
                Imprimir "Este es el resultado actual de las sumas: " a;
                Imprimir "Presione cualquier tecla para continuar.";
                Esperar Tecla;
                Limpiar Pantalla;
            caso 3: 
                Limpiar Pantalla;
                Imprimir "Bye =)";
                exit = Verdadero;
            De Otro Modo:
                Imprimir "Opcion invalida."; 
                Imprimir "Presione cualquier tecla para continuar.";
                Esperar Tecla;
                Limpiar Pantalla;
        FinSegun
        
    Hasta Que exit
FinAlgoritmo
  • Escriba un programa en pseudo-codigo que pida al usuario un numero mayor que 10 (Hacer-Mientras), después sume todos los números con un acumulador (Mientras) Ejemplo: El usuario introduce 15. El programa suma 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15.

Cada tarea 2.5 pts

Puedes consultar las clases anteriores:
Basic programming course: Lesson #1 - Introduction to programming [ESP-ENG]
Basic programming course: Lesson #2 - Variables and Types of Data [ESP-ENG]
Basic programming course: Lesson #3 Operations [ESP-ENG]
Basic programming course: Lesson #4 Control structures. Part 1. Conditionals. [ESP-ENG]

Normas


  • El contenido debe ser #steemexclusive.
  • El artículo debe contener la etiqueta #devjr-s20w5.
  • El plagio no está permitido.
  • El link de tu tarea debe ser agregado en los comentarios de esta publicación.
  • El curso estará abierto durante 7 días a partir de las 00:00 UTC del 7 de Octubre. Después de la fecha limite los usuarios podrán seguir participando sin optar a premios con el objetivo de permitir a mas personas en el tiempo de aprovechar este contenido.

ENG

Untitled design.png


Repetitive structures


We have already seen how we can make our programs make decisions for us, allowing us to follow one path or another after analyzing some data. Now we are going to learn to use one of the most important control structures of programming and surely many will have noticed it, but many of the tasks we program are quite repetitive, that is, the same task but with a small modification, so today we will know the repetitive structures that as their name indicates are structures that will help you repeat a part of the code according to a condition, as long as the condition is true the structure will continue to repeat the instruction, and once the condition is returned to False the repetitive structure will end and the program will continue its usual cycle.


Counters and accumulators


Before starting to explain the cycles I would like to clarify these two concepts that we will use a lot while we are repeating code with the cycles. Counters and accumulators are technically simply variables that we will use to count or accumulate values as their name indicates.

That is, with a counter we could count the number of times a cycle has repeated the code, and with an accumulator we could add in each repetition of the cycle a value that the user provides us.

The difference between each one is that the counter increases its value one by one as if it were counting normally and the accumulator can increase its value in a variable way depending on the needs of the program. We will see this more clearly in the examples.


Cycles


  • While: to use the cycle while we will use the word "While" followed by the condition that must be met for the cycle to be executed, and finally the word "Do". Right at the end of the structure we will place the word "EndWhile". Everything that is within this structure will be repeated according to the condition we have established, for example we will perform this exercise by defining two integer variables, a counter and an accumulator. Both variables must receive an initial value, in the case of the counter it usually starts at 1 because it will start counting from there, and the accumulator at 0 because it has not yet received any value to start adding.
Define c, a As Integer;
    c = 1;
    a = 0;

We are going to make a cycle that runs 10 times then to the condition of the cycle while it will be that as long as the counter is less than or equal to 10 then the condition will continue to repeat.

While c <=10 Do
        // All repeated here
    EndWhile

Now within the cycle what we will do is simply print a message with the accumulator and counter values. In this case I will also print a line to separate a little the information that is printed in each cycle.

Print  "Cont: " c;
        Print "Acum: " a;
        Print "-------------------------------------";

Now, right at the end of the cycle we must modify the values of the variables, if we do not do this we will create an infinite cycle and our computer may not resist it since it will be a lot of information that will be running infinitely, so we have to be careful when creating the cycles and that the logic is correct to avoid these situations. What we have to do is simply add 1 to the counter and add what is needed to the accumulator, in this case I will simply add the value of the counter each time. This is achieved like this:

c = c + 1;
a = a + c;

What we are doing is saying that c is equal to c +1, if we analyze the program a little we will see that c started with an initial value of 1, in the first round of the cycle we will add c with 1, which would be equal to 1+1. The result of this operation is 2, so in the next round c already has a value of 2. And we repeat this operation again, c+1, knowing that c now has a value of two then the operation would be 2+1, which results in 3. And in the next round we repeat this each time and so we increase the value of c with each round of the cycle. Once c has a value of 11 the cycle will stop since the condition will now be false.

In the same way we work with the accumulators, in this case I simply accumulated the value of c. The code would be as follows:

Algorithm cycles
    Define c, a As Integer;
    c = 1;
    a = 0;
    While c <=10 Do
        Print  "Cont: " c;
        Print "Acum: " a;
        Print "-------------------------------------";
        c = c + 1;
        a = a + c;
    EndWhile
EndAlgorithm

If we execute this code we will see the following:

Captura de pantalla 2024-10-06 a la(s) 11.12.29 a. m..png

  • For: the cycle for is quite similar to the previous cycle, only in this case the same cycle will have the counter declared implicitly and we will not have to worry about handling it, generally the cycle counter for is a variable called i, and it is not necessary to declare it since within the same cycle it is done automatically. Using this cycle is very simple, we will simply put the word "For" followed by the name of the counter variable, in this case as I already mentioned the convention is to use the letter i. Then we will use the word "from" followed by the number where the cycle will begin, that is, the initial value of and then the word "to" followed by the number until where the cycle will run.

To show you the example, we will simply make a cycle that runs five times, so it would be as follows:

For i from 1 to 5 do
        Print i; 
    EndFor 

Here we are simply running the cycle five times and we are showing the variable i so that they can check its value in each round of the cycle. If we execute this code we will have the following:

Captura de pantalla 2024-10-06 a la(s) 11.56.19 a. m..png

  • Do-While: technically this cycle is the same as the while cycle, only that this previous one must meet the condition so that you can run the whole cycle, however, the do-while cycle will run once and then evaluate the condition that will determine if it will continue to run or if it will stop immediately. We can see this more clearly with an example, suppose we want to ask for the age of a user, but this cannot be less than 18, so we can make a cycle that continues to run infinitely as long as the age provided is not greater than or equal to 18, let's try it.

First we are going to declare the variables, in this case a name and an age. Then we are going to ask for the name as we normally would.

Define age as Integer;
Define name as Character;

Print "Enter your name:";
Read name;

Here we will start the cycle, we will put the word "Repeat" and we will close this structure with the words "Until" followed by the condition to be evaluated. Everything that is within that structure will be repeated until the condition is true as its name suggests.

We are going to request the age of the user normally. I put a small conditional at the end of the cycle that evaluates if the age is less than 18, in this case it shows the user a message that tells him to try again since he must be of legal age.

Repeat
        Print "Enter your age:";
        Read age;
        
        If (edad < 18)
            Print "try again.";
        EndIf
    Until age >= 18

This instruction works as follows: the user will enter his age, if his age is less than 18 then the message of what he should try again will be displayed, as the instruction does not meet the condition of until then it will be repeated again and will ask again the user's age, this will do so until the program receives a value greater than or equal to 18.

Let's see the execution:

Captura de pantalla 2024-10-06 a la(s) 2.33.56 p. m..png


Example


We are going to create a program that asks the user how many names he wants to enter, and from there run a cycle to ask for each of the names, then at the end of the exercise the list with all the names will be displayed.

To do this we will have to create three variables, one to create the list of names that will be a text accumulator, a variable to read each name, and an integer variable to ask how many names the user wants to enter.

We will initialize the name accumulator variable as an empty text string, for this we will put the two " with nothing between them. Then we will ask how many names you want to enter.

Define names, name As Character;
    Define n As Integer;
    
    names = "";
    
    Print "How much names do you want to read?";
    Read n;

Then we will make a Para cycle that will go from 1 to n which is the variable where we will store the number of names that the user wants to enter. Within the cycle we will begin to read all the names and accumulate them in the variables names. We say that names are equal to names, we add a space and the variable name that we just read in that round of the cycle. So all the names will be stored in this string that we will print just at the end of the cycle.

For i from 1 to n Do
        Print "Enter a name";
        Read name;
        
        names = names + " " + name;
    EndFor
    
    Print "List: " names;

This executed code would look like this:

Captura de pantalla 2024-10-06 a la(s) 2.39.15 p. m..png


Homework


  • Explain the cycles in detail. What are they and how are they used? What is the difference between the While and Do-While cycle?
  • Investigate how the Switch-case structure is used and give us an example.
  • Explain what the following code does:
Algorithm switchcase
    Define  op, n, ns, a As Integer;
    Define exit As Logic;
    
    exit = False;
    a=0;
    
    Repeat 
        Print  "Select an option:";
        Print  "1. Sum numbers.";
        Print  "2. Show results."
        Print  "3. End program."; 
        Read op;
        
        Switch op Do
            case 1:
                Print "How much nums do you want to sum?";
                Read n; 
                For i from 1 to n Do
                    Print "Enter a number: ";
                    Read ns; 
                    a = a + ns;
                EndFor
                Print "Completed! Press any button to continue";
                Wait Key;
                Clear Screen;
            case 2:
                Print "This is the current result: " a;
                Print "Press any button to continue.";
                Wait Key;
                Clear Screen;
            caso 3: 
                Clear Screen;
                Print "Bye =)";
                exit = True;
            Default:
                Print "Invalid option."; 
                Print "Press any button to continue";
                Wait Key;
                Clear Screen;
        EndSwitch
        
    Until exit
EndAlgorithm
  • Write a program in pseudo-code that asks the user for a number greater than 10 (Do-While), then add all the numbers with an accumulator (While) Example: The user enters 15. The program adds up to 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15.

Each task 2.5 pts

You can check the previous classes:
Basic programming course: Lesson #1 - Introduction to programming [ESP-ENG]
Basic programming course: Lesson #2 - Variables and Types of Data [ESP-ENG]
Basic programming course: Lesson #3 Operations [ESP-ENG]
Basic programming course: Lesson #4 Control structures. Part 1. Conditionals. [ESP-ENG]

Rules


  • The content must be #steemexclusive.
  • The article must contain the tag #devjr-s20w5.
  • Plagiarism is not allowed.
  • The link of your task must be added in the comments of this publication.
  • The course will be open for 7 days from 00:00 UTC on October 7. After the deadline, users will be able to continue participating without applying for prizes with the aim of allowing more people in time to take advantage of this content.
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
Loading...

Getting more interesting each week.

Yes, now you can do programs a little more complex!

I read it carefully and now I think I have an headache .. it's way more complex now ,,, Hahaha.

Dont read too much and practice, you will see more clearly how it works!