The slide "Recorrer arrays" compares two methods for iterating over arrays in C#. The left column explains using a for loop with indices for precise positional control, as shown in an example that prints array elements from index 0 to Length-1. The right column describes the foreach loop for directly accessing elements sequentially without indices, highlighting its simplicity and suitability for read-only traversals.
Recorrer arrays
| For usando índices | Foreach recorriendo elementos |
|---|
| Utiliza un bucle for con índices para acceder a elementos específicos. Ejemplo:
int[] numeros = {1, 2, 3, 4, 5}; for (int i = 0; i < numeros.Length; i++) { Console.WriteLine(numeros[i]); }
Permite control preciso sobre la posición. | Recorre directamente los elementos sin índices. Más simple y legible. Ejemplo:
int[] numeros = {1, 2, 3, 4, 5}; foreach (int num in numeros) { Console.WriteLine(num); }
Ideal para iteraciones secuenciales sin modificar el array. |