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}");Desafío
FácilCrea un método llamado countElements que:
- Toma un arreglo jagged de cadenas (string[][]) como parámetro
- Cuenta cuántos elementos hay en todo el arreglo jagged
- 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í
}
}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
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety