Tablice dwuwymiarowe int[,] i GetLength
Tablice - Podstawy C# (csharp)
Tablica prostokątna
int[,] ma wiersze i kolumny jednakowej długości. Element odczytujemy zapisem matrix[wiersz, kolumna]. Length podaje liczbę WSZYSTKICH elementów, a GetLength(0) liczbę wierszy i GetLength(1) liczbę kolumn. Tablicę wypisujemy dwiema zagnieżdżonymi pętlami; znak \t (tabulator) wyrównuje kolumny.using System;
class Program
{
static void Main(string[] args)
{
int[,] matrix =
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
Console.WriteLine("Wiersze: " + matrix.GetLength(0));
Console.WriteLine("Kolumny: " + matrix.GetLength(1));
Console.WriteLine("Wszystkich elementów: " + matrix.Length);
for (int row = 0; row < matrix.GetLength(0); row++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
Console.Write(matrix[row, col] + "\t");
}
Console.WriteLine();
}
// tabliczka mnożenia 3 x 4 tworzona pętlami
int[,] table = new int[3, 4];
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 4; col++)
{
table[row, col] = (row + 1) * (col + 1);
}
}
Console.WriteLine("Element [2, 3] tabliczki: " + table[2, 3]);
}
}Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.
Wszystkie lekcje kursu Podstawy C#·Zaloguj się, aby zapisać postęp na koncie.