Arrays (Single & Multi-Dimensional)

🔷 C# Programming Lesson 6 Beginner

Arrays allocate a contiguous block of memory to store values of a single data type. C# supports single-dimensional, multi-dimensional (rectangular), and jagged arrays.

1 Rectangular vs. Jagged Arrays

C# distinguishes between two types of multi-dimensional arrays:

  • Rectangular Array (`int[,] matrix`): A single block of memory representing a grid (e.g. 3x3) where every row is guaranteed to have the same length.
  • Jagged Array (`int[][] jagged`): An "array of arrays" where each row can have a different length, saving memory for non-uniform data.
2 Array Operations

Let's run a program declaring single arrays, rectangular matrices, and iterating values:

C# — Arrays ▶ Run Code
using System;

class Program {
    static void Main() {
        // Single-dimensional array
        int[] scores = { 90, 85, 78, 92 };

        // Rectangular 2D array (Rows x Columns)
        int[,] matrix = {
            { 1, 2, 3 },
            { 4, 5, 6 }
        };

        Console.WriteLine("Iterating rectangular matrix:");
        for (int r = 0; r < matrix.GetLength(0); r++) {
            for (int c = 0; c < matrix.GetLength(1); c++) {
                Console.Write(matrix[r, c] + " ");
            }
            Console.WriteLine();
        }
    }
}
3 Code Challenge
Challenge: Write a program that declares a jagged array containing 3 rows. Initialize row 0 with 2 items, row 1 with 4 items, and row 2 with 3 items. Iterate through the array and print all values.