Массивы
Массив хранит фиксированное число значений одного типа, и к каждому обращаются по индексу, начиная с 0.
Как это работает
Создавайте, читайте, изменяйте, обходите и сортируйте массивы C#, включая двумерные.
Length даёт размер, а ^1 читает последний элемент. foreach обходит все элементы, Array.Sort сортирует на месте, new int[3] начинается с нулей, а int[,] создаёт сетку с индексами строки и столбца.
Как это работает
Щёлкните по ячейке или двигайте ползунок, чтобы выбрать индекс. Вставьте или удалите элемент и посмотрите, почему все следующие элементы должны сдвинуться.
Пример на C#, который можно запустить
using System;
using System.Linq;
class Program
{
static void Main()
{
// An array has a fixed length set when it is created.
int[] scores = { 72, 95, 88, 64 };
Console.WriteLine($"Length: {scores.Length}");
Console.WriteLine($"First: {scores[0]}, last: {scores[^1]}");
scores[3] = 70; // elements can be changed, the length cannot
int sum = 0;
foreach (int score in scores)
{
sum += score;
}
Console.WriteLine($"Sum: {sum}, average: {sum / (double)scores.Length}");
// Array.Sort sorts in place; string.Join prints the elements.
Array.Sort(scores);
Console.WriteLine($"Sorted: {string.Join(", ", scores)}");
Console.WriteLine($"Max: {scores.Max()}");
// new int[3] creates an array of zeros.
int[] counts = new int[3];
counts[1] = 5;
Console.WriteLine($"Counts: {string.Join(" ", counts)}");
// A 2D array is indexed by row and column.
int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
Console.WriteLine($"grid[1, 2] = {grid[1, 2]}");
}
}
Length: 4
First: 72, last: 64
Sum: 325, average: 81.25
Sorted: 70, 72, 88, 95
Max: 95
Counts: 0 5 0
grid[1, 2] = 6Практика с отладчиком
Попрактикуйтесь на задаче
Примените материал этого урока к реальной задаче. Каждая задача запускается в браузере, с мгновенными тестами и разбором от ИИ.
- Count Positive Numbers Count the values greater than zero in a list. Легко
- Running Sum Replace each value with the total so far. Легко
- Swap First and Last Exchange the first and last items of a list. Легко