Mảng
Mảng lưu một số lượng cố định giá trị cùng kiểu, mỗi giá trị được truy cập qua chỉ số bắt đầu từ 0.
Cách hoạt động
Tạo, đọc, thay đổi, duyệt và sắp xếp mảng C#, kể cả mảng hai chiều.
Length cho biết kích thước và ^1 đọc phần tử cuối. foreach đi qua mọi phần tử, Array.Sort sắp xếp tại chỗ, new int[3] khởi đầu bằng các số 0, còn int[,] tạo lưới truy cập theo hàng và cột.
Xem cách hoạt động
Nhấp vào một ô hoặc kéo thanh trượt để chọn chỉ số. Chèn hoặc xóa để thấy vì sao mọi phần tử phía sau phải dịch chuyển.
Ví dụ C# chạy đượ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] = 6Luyện tập với trình gỡ lỗi
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
- Count Positive Numbers Count the values greater than zero in a list. Dễ
- Running Sum Replace each value with the total so far. Dễ
- Swap First and Last Exchange the first and last items of a list. Dễ