Menu
Coddy logo textTech

Iterare strutture complesse

Fa parte della sezione Logica e flusso del percorso C# di Coddy. Lezione 14 di 66.

Iterare attraverso strutture complesse come gli array annidati richiede approcci speciali.

Scorri un array 2D usando cicli annidati:

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]);
    }
}

Scorri un array di stringhe ed elabora ogni carattere:

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]);
    }
}

Conta gli elementi in un array frastagliato:

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

Sfida

Facile

Crea un metodo chiamato countElements che:

  1. Accetta come parametro un array frastagliato di stringhe (string[][])
  2. Conta quanti elementi ci sono nell’intero array frastagliato
  3. Restituisce il conteggio totale

Per esempio, dato:

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

Il risultato dovrebbe essere 6 (3 + 2 + 1).

Provalo tu

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

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore C# online