Menu
Coddy logo textTech

Iterating Complex

Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 14 de 66.

Iterar a través de estructuras complejas como arrays anidados requiere enfoques especiales.

Itera a través de un arreglo 2D usando bucles anidados:

int[][] matrix = new int[3][];
matrix[0] = new int[] { 1, 2, 3 };
matrix[1] = new int[] { 4, 5, 6 };
matrix[2] = new int[] { 7, 8, 9 };

for (int i = 0; i < matrix.Length; i++)
{
    for (int j = 0; j < matrix[i].Length; j++)
    {
        Console.WriteLine(matrix[i][j]);
    }
}

Recorrer un arreglo de cadenas y procesar cada carácter:

string[] words = { "hello", "world" };

for (int i = 0; i < words.Length; i++)
{
    for (int j = 0; j < words[i].Length; j++)
    {
        Console.WriteLine(words[i][j]);
    }
}

Contar elementos en un array irregular:

int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6 };

int totalItems = 0;
for (int i = 0; i < jaggedArray.Length; i++)
{
    totalItems += jaggedArray[i].Length;
}
Console.WriteLine($"Total items: {totalItems}");
challenge icon

Desafío

Fácil

Crea un método llamado countElements que:

  1. Toma un arreglo jagged de cadenas (string[][]) como parámetro
  2. Cuenta cuántos elementos hay en todo el arreglo jagged
  3. Devuelve el conteo total

Por ejemplo, dado:

[
  ["apple", "orange", "apple"],
  ["banana", "apple"],
  ["orange"]
]

El resultado debería ser 6 (3 + 2 + 1).

Hoja de referencia

Usa bucles anidados para iterar a través de arreglos 2D:

int[][] matrix = new int[3][];
matrix[0] = new int[] { 1, 2, 3 };
matrix[1] = new int[] { 4, 5, 6 };
matrix[2] = new int[] { 7, 8, 9 };

for (int i = 0; i < matrix.Length; i++)
{
    for (int j = 0; j < matrix[i].Length; j++)
    {
        Console.WriteLine(matrix[i][j]);
    }
}

Itera a través de arreglos de cadenas y accede a caracteres individuales:

string[] words = { "hello", "world" };

for (int i = 0; i < words.Length; i++)
{
    for (int j = 0; j < words[i].Length; j++)
    {
        Console.WriteLine(words[i][j]);
    }
}

Cuenta el total de elementos en un arreglo irregular:

int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6 };

int totalItems = 0;
for (int i = 0; i < jaggedArray.Length; i++)
{
    totalItems += jaggedArray[i].Length;
}
Console.WriteLine($"Total items: {totalItems}");

Pruébalo tú mismo

using System;
public class CountElements
{
    // Implementa el método countElements
    public static int countElements(string[][] nestedArray)
    {
        // Escribe tu código aquí
        
    }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Lógica y Flujo