Menu
Coddy logo textTech

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}");
challenge icon

Desafio

Fácil

Crie um método chamado countElements que:

  1. Recebe um array irregular de strings (string[][]) como parâmetro
  2. Conta quantos elementos há no array irregular inteiro
  3. 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
        
    }
}
quiz iconTeste seus conhecimentos

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