Manufactura industrial
Internet industrial de las cosas | Materiales industriales | Mantenimiento y reparación de equipos | Programación industrial |
home  MfgRobots >> Manufactura industrial >  >> Industrial programming >> Lenguaje C

Matriz irregular de C#

Arreglo irregular de C#

En este tutorial, aprenderemos sobre la matriz irregular de C#. Aprenderemos a declarar, inicializar y acceder a la matriz irregular con la ayuda de ejemplos.

En C#, una matriz irregular consta de varias matrices como su elemento. Sin embargo, a diferencia de las matrices multidimensionales, cada matriz dentro de una matriz irregular puede tener diferentes tamaños.

Antes de aprender sobre la matriz irregular, asegúrese de conocer


Declaración de matriz irregular de C#

Aquí hay una sintaxis para declarar una matriz irregular en C#.

dataType[ ][ ] nameOfArray = new dataType[rows][ ];

Veamos un ejemplo,

// declare jagged array
int[ ][ ] jaggedArray = new int[2][ ];

Aquí,

Como sabemos que cada elemento de una matriz irregular también es una matriz, podemos establecer el tamaño de la matriz individual. Por ejemplo,

// set size of the first array as 3
jaggedArray[0] = new int[3];

// set size of second array as 2
jaggedArray[1] = new int[2];

Inicializando matriz irregular

Hay diferentes formas de inicializar una matriz irregular. Por ejemplo,

1. Usando el número de índice

Una vez que declaramos una matriz irregular, podemos usar el número de índice para inicializarla. Por ejemplo,

// initialize the first array
jaggedArray[0][0] = 1;
jaggedArray[0][1] = 3;
jaggedArray[0][2] = 5;

// initialize the second array
jaggedArray[1][0] = 2;
jaggedArray[1][1] = 4;

Aquí,

2. Inicializar sin configurar el tamaño de los elementos de la matriz

// declaring string jagged array
int[ ][ ] jaggedArray = new int[2] [ ];

// initialize each array
jaggedArray[0] = new int[] {1, 3, 5};
jaggedArray[1] = new int[] {2, 4};

3. Inicializar mientras se declara Jagged Array

int[ ][ ] jaggedArray = {
    new int[ ] {10, 20, 30},
    new int[ ] {11, 22},
    new int[ ] {88, 99}
};

Acceso a elementos de una matriz irregular

Podemos acceder a los elementos de la matriz irregular utilizando el número de índice. Por ejemplo,

// access first element of second array
jaggedArray[1][0];

// access second element of the second array
jaggedArray[1][1];

// access second element of the first array
jaggedArray[0][1];

Ejemplo:C# Matriz irregular

using System;

namespace JaggedArray {
  class Program {
    static void Main(string[] args) {

     // create a jagged array
     int[ ][ ] jaggedArray = {
         new int[] {1, 3, 5},
         new int[] {2, 4},
      };

     // print elements of jagged array
     Console.WriteLine("jaggedArray[1][0]: " + jaggedArray[1][0]);
     Console.WriteLine("jaggedArray[1][1]: " + jaggedArray[1][1]);

     Console.WriteLine("jaggedArray[0][2]: " + jaggedArray[0][2]);

     Console.ReadLine();
    }    
  }
}

Salida

jaggedArray[1][0]: 2
jaggedArray[1][1]: 4
jaggedArray[0][2]: 5

Aquí, dentro de una matriz irregular,


Iterando a través de una matriz irregular

En C#, podemos usar bucles para iterar a través de cada elemento de la matriz irregular. Por ejemplo,

using System;

namespace JaggedArray {
  class Program {
    static void Main(string[] args) {

      // declare a jagged array
      int[][] jaggedArray = new int[2][];

      // set size of Jagged Array Elements
      jaggedArray[0] = new int[3];
      jaggedArray[1] = new int[2];

      // initialize the first array
      jaggedArray[0][0] = 1;
      jaggedArray[0][1] = 3;
      jaggedArray[0][2] = 5;

      // initialize the second array
      jaggedArray[1][0] = 2;
      jaggedArray[1][1] = 2;
      	 
      // outer for loop
      for (int i = 0; i < jaggedArray.Length; i++) {

        Console.Write("Element "+ i +": ");
        // inner for loop
        for (int j = 0; j < jaggedArray[i].Length; j++) {
          Console.Write(jaggedArray[i][j] + " ");
         }
      Console.WriteLine();
      }
      Console.ReadLine();
    } 
  }
}

Salida

Element 0: 1 3 5
Element 1: 2 2

En el ejemplo anterior, hemos usado un bucle for anidado para iterar a través de la matriz irregular. Aquí,

1. Bucle for exterior

2. Bucle for interno


Matriz irregular con matriz multidimensional

En C#, también podemos usar matrices multidimensionales como elementos de matriz irregular. Por ejemplo,

int[ ][ , ] jaggedArrayTwoD = new int[2][ , ] {
    	new int[,] { {1, 8}, {6, 7} },
    	new int[,] { {0, 3}, {5, 6}, {9, 10} }
};

Aquí, cada elemento de la matriz irregular es una matriz multidimensional:

Veamos un ejemplo,

using System;

namespace JaggedArray  {
  class Program {
    static void Main(string[] args)  {
  	 
      // declare and initialize jagged array with 2D array
      int[][,] jaggedArray = new int[3][ , ]  {
          new int[ , ] { {1, 8}, {6, 7} },
          new int[ , ] { {0, 3}, {5, 6}, {9, 10} },
          new int[ , ] { {11, 23}, {100, 88}, {0, 10} }
      };

      Console.WriteLine(jaggedArray[0][0, 1]);
      Console.WriteLine(jaggedArray[1][2, 1]);
      Console.WriteLine(jaggedArray[2][1, 0]);

      Console.ReadLine();
    }    
  }
}

Salida

8
10
100

En el ejemplo anterior, observe el código,

jaggedArray[0][0, 1]

Aquí,


Lenguaje C

  1. Matrices de C#
  2. Matriz multidimensional de C#
  3. Pasar matriz a una función en programación C++
  4. Matrices de copia de Java
  5. Matrices en C++ | Declarar | Inicializar | Ejemplos de puntero a matriz
  6. C++ Asignación dinámica de arreglos con ejemplo
  7. Tutorial de colecciones de C# con ejemplos
  8. Cómo crear una matriz de objetos en Java
  9. MATLAB - Matrices
  10. Técnicas de inspección de matriz de rejilla de bolas
  11. Matriz de nanosensores de lengua electrónica