Массивы в C#
Массив в C#:
- Массив - это коллекция того же типа данных
- Массив может быть объявлен как фиксированный размер или динамический
- Массив может быть доступен по индексу
- Индекс массива начинается с 0, поэтому первый элемент массива начинается с 0-й позиции.
Пример :
class ArrayExample
{
static void Main(string[] args)
{
int[] number = new int[5];
number[0] = 100;
number[1] = 200;
number[2] = 300;
number[3] = 400;
number[4] = 500;
foreach (int val in number)
{
Console.WriteLine(val);
}
Console.ReadKey();
}
}
Вывод:
100
200
300
400
500
В C# имеется 2 типа массива.
- Одномерный массив в C#:
- Многомерный массив в C#:
Одномерный массив в C#:
В одном массиве измерений нам нужен только один индекс для доступа к элементу массива.
Пример:
class ArrayExample
{
static void Main(string[] args)
{
// Создайте одномерный массив.
int[] arr = new int[5];
for (int x = 0; x < 5; x++)
{
Console.WriteLine("Enter array element : ", x);
arr[x] = Int32.Parse(Console.ReadLine());
}
foreach (int i in arr)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
Многомерный массив в C#:
C# позволяет многомерный массив. это может быть 2-мерный массив или 3-мерный массив.
class ArrayExample
{
static void Main(string[] args)
{
// Создайте трехмерный массив.
int[, ,] threeDimensional = new int[3, 5, 4];
threeDimensional[0, 0, 0] = 1;
threeDimensional[0, 1, 0] = 2;
threeDimensional[0, 2, 0] = 3;
threeDimensional[0, 3, 0] = 4;
threeDimensional[0, 4, 0] = 5;
threeDimensional[1, 1, 1] = 2;
threeDimensional[2, 2, 2] = 3;
threeDimensional[2, 2, 3] = 4;
for (int i = 0; i < threeDimensional.GetLength(2); i++)
{
for (int y = 0; y < threeDimensional.GetLength(1); y++)
{
for (int x = 0; x < threeDimensional.GetLength(0); x++)
{
Console.Write(threeDimensional[x, y, i]);
}
Console.WriteLine();
}
Console.WriteLine();
}
}
}
