Menu
Coddy logo textTech

2D Arrays Basics

Parte de la sección Lógica y Flujo del Journey de C# de Coddy — lección 1 de 66.

En C#, un array irregular es un array de arrays, que forma una estructura de cuadrícula o similar a una matriz. Es como una tabla con filas y columnas, donde cada celda puede contener un valor. Los arrays irregulares son útiles para representar datos que tienen una relación bidimensional, como un tablero de ajedrez, un plano de asientos o un juego basado en cuadrícula.

Aquí se muestra cómo declarar e inicializar un array irregular en C#:

data_type[][] arrayName = new dataType[numberOfRows][];

dataType: El tipo de elementos que el arreglo contendrá (p. ej., int, string, etc.).

arrayName: El nombre que le das al arreglo.

numberOfRows: El número de filas en el arreglo.

Cada fila debe inicializarse entonces por separado:

arrayName[0] = new dataType[lengthOfFirstRow];
arrayName[1] = new dataType[lengthOfSecondRow];
// and so on...

Por ejemplo, para crear un arreglo irregular de enteros con 3 filas, donde cada fila tiene 4 columnas, escribirías:

int[][] matrix = new int[3][];
matrix[0] = new int[4];
matrix[1] = new int[4];
matrix[2] = new int[4];

También puedes inicializar un array irregular directamente con valores:

int[][] matrix = new int[][] {
    new int[] {1, 2, 3},
    new int[] {4, 5, 6},
    new int[] {7, 8, 9}
};
challenge icon

Desafío

Fácil

Inicializa un arreglo irregular con los siguientes valores:

5, 7, 10, 24, 41
86, 13, 683, 64, 13
42, 46, 791, 111, 9
86, 88, 1845, 5, 15897
9, 1, 5, 5, 6

Tu tarea es inicializar correctamente el arreglo irregular con estos valores exactos y asegurarte de que el programa imprima correctamente la matriz.

Hoja de referencia

Un arreglo jagged es un arreglo de arreglos, que forma una estructura similar a una matriz con filas y columnas.

Sintaxis de declaración:

data_type[][] arrayName = new dataType[numberOfRows][];

Cada fila debe inicializarse por separado:

arrayName[0] = new dataType[lengthOfFirstRow];
arrayName[1] = new dataType[lengthOfSecondRow];

Ejemplo con inicialización separada:

int[][] matrix = new int[3][];
matrix[0] = new int[4];
matrix[1] = new int[4];
matrix[2] = new int[4];

Inicialización directa con valores:

int[][] matrix = new int[][] {
    new int[] {1, 2, 3},
    new int[] {4, 5, 6},
    new int[] {7, 8, 9}
};

Pruébalo tú mismo

using System;

class Program
{
    static void Main(string[] args)
    {
        int[][] matrix = {
            // Escribe tu código aquí
        };
        
        // Imprime la matriz
        int rows = matrix.Length;
        
        for (int i = 0; i < rows; i++)
        {
            int cols = matrix[i].Length;
            for (int j = 0; j < cols; j++)
            {
                Console.Write(matrix[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Lógica y Flujo