Menu
Coddy logo textTech

Iterating Complex

Part of the Logic & Flow section of Coddy's C# journey — lesson 14 of 66.

Iterating through complex structures like nested arrays requires special approaches.

Iterate through a 2D array using nested loops:

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

Iterate through a string array and process each character:

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

Count items in a jagged array:

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

Challenge

Easy

Create a method called countElements that:

  1. Takes a jagged array of strings (string[][]) as a parameter
  2. Counts how many elements are in the entire jagged array
  3. Returns the total count

For example, given:

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

The result should be 6 (3 + 2 + 1).

Cheat sheet

Use nested loops to iterate through 2D arrays:

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

Iterate through string arrays and access individual characters:

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

Count total items in a jagged array:

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

Try it yourself

using System;
public class CountElements
{
    // Implement the countElements method
    public static int countElements(string[][] nestedArray)
    {
        // Write your code here
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow