配列
配列は同じ型の値を決まった数だけ保存し、それぞれ 0 から始まる添字で参照します。
仕組み
C# の配列を作り、読み、変更し、走査し、並べ替えます。2 次元配列も扱います。
Length でサイズが分かり、^1 で最後の要素を読めます。foreach は全要素をたどり、Array.Sort はその場で並べ替え、new int[3] は 0 で始まり、int[,] は行と列で参照する格子を作ります。
動きで理解する
箱をクリックするかスライダーでインデックスを選びます。挿入や削除をすると、後ろの要素がすべてずれる理由がわかります。
実行できる C# の例
C#
Program.cs
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デバッガーで練習する
大事な代入や条件にブレークポイントを置いて Debug を押し、次の行に進む前にローカル変数の値を確かめましょう。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
- Count Positive Numbers Count the values greater than zero in a list. 簡単
- 累積和 各値を、それまでの合計値に置き換えます。 簡単
- 最初と最後を入れ替える リストの最初と最後の要素を交換します。 簡単