Contenido del Curso
Principios Básicos de Java
Principios Básicos de Java
Loop For
A major drawback of the while
loop is that we can't specify an exact number of iterations and fully control the loop's execution. That's why the for
loop exists, which provides us with all the tools for proper loop control and is also used when working with arrays and collections. It's a cool thing.
Uno de los principales inconvenientes del loop while
es que no podemos especificar un número exacto de iteraciones y controlar totalmente la ejecución del loop. Por eso existe el loop for
, que nos proporciona todas las herramientas para un control adecuado del loop y también se utiliza cuando trabajamos con arrays y colecciones. Es algo genial.
Loop For
El loop for es una sentencia de flujo de control que permite ejecutar repetidamente un bloque de código un número determinado de veces. Se suele utilizar cuando se conoce el número exacto de iteraciones o cuando se itera sobre una colección o array.
Main
for (initialization; condition; update) { // code to be executed }
If we go step by step, initially, we initialize a variable in a special section for it (we did the same for the while
loop, only we did it outside the loop). Then we set the condition for when the loop should run (for example, as long as the variable is less than 10). After that, in the third section, we use an increment or decrement. Below is a flowchart and an explanation of the operation of each of the loop blocks:
Here's the breakdown of each part of the for loop:
- Initialization: This is the initial setup executed only once at the beginning of the loop. Typically, you declare and initialize a loop control variable here. For example,
int i = 0
; - Condition: This is the condition checked before each iteration. If the condition is true, the loop body is executed. If the condition is false, the loop terminates. For example,
i < 10
; - Increment/Decrement Expression: This is the code executed after each iteration. Typically, you update the loop control variable here. For example,
i++
(which is equivalent toi = i + 1
); - Code Inside Loop: This is the block of code executed for each iteration of the loop. You can put any valid Java code inside the loop body.
Aquí está el desglose de cada parte del loop for:
- Inicialización: Esta es la configuración inicial ejecutada sólo una vez al comienzo del loop. Típicamente, aquí se declara e inicializa una variable de control del loop. Por ejemplo,
int i = 0
; - Condición: Es la condición que se comprueba antes de cada iteración. Si la condición es verdadera, se ejecuta el cuerpo del loop. Si la condición es falsa, el loop termina. Por ejemplo,
i < 10
; - Expresión de Incremento/Decremento: Es el código que se ejecuta después de cada iteración. Normalmente, aquí se actualiza la variable de control del loop. Por ejemplo,
i++
(que equivale ai = i + 1
); - Código dentro del loop: Este es el bloque de código que se ejecuta en cada iteración del loop. Puedes poner cualquier código Java válido dentro del cuerpo del loop.
Main
package com.example; public class Main { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println("Iteration: " + i); } } }
In this example, the loop will execute 10 times. It starts with i
initialized to 0
, checks if i
is less than 10
, executes the loop body, and then updates i
by incrementing it by 1
. This process repeats until the condition becomes false.
It's worth noting that in this loop, we can use the variable we created. In our case, we output the variable i
to display the iteration number on the screen.
This is very useful, especially when we need our variable i
to be involved in the code.
Let's look at another example where we need to display only even numbers in the range from 1 to 30:
main
package com.example; public class Main { public static void main(String[] args) { for (int i = 0; i < 30; i++) { if (i % 2 == 0) { // check if `i` is even System.out.println(i); } } } }
Great, in the code above, we used the variable i
when checking the condition. In other words, i
represents the numbers we are considering. Next, we check if the number i
is even using the modulo operation (%
). If the remainder of division by 2 is zero, then the number is even, meaning it is divisible by 2 without a remainder.
Also, pay attention to how we set the condition for i
. The algorithm of our actions remains the same as it was, but in the loop condition, we limited i
to a value of 30, as specified in the task.
1. How many iterations will be there?
2. How many times i
will be displayed
¡Gracias por tus comentarios!