Matrices or tables
C# has multidimensional arrays as well as jagged array
Creating
Initializing
int[,] matrix = new int[2, 4];
int[,] matrix =
{
// cols
// 0 1 2 3
{ 1, 2, 3, 4 }, // row 0
{ 5, 6, 7, 8 } // row 1
};
1 | 2 | 3 | 4 |
---|
5 | 6 | 7 | 8 |
---|
Accessing the elements of the matrix
Console.WriteLine(matrix[0, 0]); // 1
Console.WriteLine(matrix[1, 2]); // 7
Console.WriteLine(matrix[1, 4]); // Out of boundaries
Could have more than 2 dimensions
int[,,] cube =
{
{
{ 1, 2, 3 },
{ 4, 5, 6 }
},
{
{ 7, 8, 9 },
{ 10, 11, 12 }
}
};
1 | 2 | 3 | 4 | 5 |
---|
0 | -1 | -2 |
---|
8 | 7 | 6 | 5 |
---|
int[][] jagged = new int[3][];
jagged[0] = new int[5] {1, 2, 3, 4, 5};
jagged[1] = new int[3] {0, -1, -2};
jagged[2] = new int[4] {8, 7, 6, 5};
// Read from the Console. It could be read from any source (ex: file)
int rows = int.Parse(Console.ReadLine());
int columns = int.Parse(Console.ReadLine());
int[,] matrix = new int[rows, columns];
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
// Interpolation strings
Console.Write($"matrix[{row},{column}] = ");
matrix[row, column] = int.Parse(Console.ReadLine());
}
}
for (int row = 0; row < matrix.GetLength(0); row++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
Console.Write("{0, 4}", matrix[row, col]);
}
Console.WriteLine();
}
int size = int.Parse(Console.ReadLine());
string[][] jagged = new string[size][];
for (int i = 0; i < size; i++)
{
string line = Console.ReadLine();
// Split the line by "," or any other symbol
string[] arrStrings = line.Split(',');
// Assign the split array to the jagged at position "i"
jagged[i] = arrStrings;
}
// jagged array from the previous example
for (int i = 0; i < jagged.Length; i++)
{
for (int j = 0; j < jagged[i].Length; j++)
{
Console.Write(jagged[i][j]);
}
Console.WriteLine();
}
// jagged array from the previous example
for (int i = 0; i < jagged.Length; i++)
{
Console.WriteLine(string.Join(",", jagged[i]));
}
int[] arr = { 1, 2, 3 };
int[] arrCopy = arr;
arr[1] = 5;
// The result is 5 because the two arrays
// points to the same address in memory
Console.WriteLine(arrCopy[1]);
// True -> The same address in memory
Console.WriteLine(arr == arrCopy);
int[][] arr = new int[2][];
arr[0] = new int[3] { 1, 2, 3 };
arr[1] = new int[1] { 2 };
// Clone and cast it to int[]
int[][] arrCopy = (int[][])arr.Clone();
arr[1][0] = 20;
// Result is 20 because the elements of the array are arrays
// and they are reference types
Console.WriteLine(arrCopy[1][0]);
// False -> Shallow copy (different arrays but the same addresses of the values)
Console.WriteLine(arr == arrCopy);