C# の基礎

配列

配列は同じ型の値を決まった数だけ保存し、それぞれ 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 のレビューも受けられます。

すべてのチャレンジ