Iterating Complex
Parte da seção Lógica & Fluxo do Journey de C# da Coddy — lição 14 de 66.
Iterar por estruturas complexas, como arrays aninhados, requer abordagens especiais.
Itere por um array 2D usando loops aninhados:
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]);
}
}Percorra um array de strings e processe cada caractere:
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 itens em um 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}");Desafio
FácilCrie um método chamado countElements que:
- Recebe um array irregular de strings (string[][]) como parâmetro
- Conta quantos elementos há no array irregular inteiro
- Retorna a contagem total
Por exemplo, dado:
[
["apple", "orange", "apple"],
["banana", "apple"],
["orange"]
]O resultado deve ser 6 (3 + 2 + 1).
Folha de consulta
Use loops aninhados para iterar por meio de arrays 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]);
}
}Itere por meio de arrays de strings e acesse caracteres individuais:
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]);
}
}Conte o total de itens em um 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}");Experimente você mesmo
using System;
public class CountElements
{
// Implemente o método countElements
public static int countElements(string[][] nestedArray)
{
// Escreva seu código aqui
}
}Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.
Todas as lições de Lógica & Fluxo
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