チュートリアル

C#基礎:条件分岐とループ

CSharp入門制御構文
広告エリア

条件分岐

if文

int age = 20;

if (age >= 20)
{
    Console.WriteLine("成人です");
}
else if (age >= 13)
{
    Console.WriteLine("ティーンエイジャーです");
}
else
{
    Console.WriteLine("子供です");
}

三項演算子

int age = 20;
string status = age >= 20 ? "成人" : "未成年";

// null合体演算子
string name = null;
string displayName = name ?? "ゲスト";  // "ゲスト"

// null条件演算子
string upper = name?.ToUpper();  // null(エラーにならない)

// null合体代入演算子
name ??= "デフォルト";  // nameがnullなら代入

switch文

int day = 3;

switch (day)
{
    case 1:
        Console.WriteLine("月曜日");
        break;
    case 2:
        Console.WriteLine("火曜日");
        break;
    case 3:
        Console.WriteLine("水曜日");
        break;
    case 6:
    case 7:
        Console.WriteLine("週末");
        break;
    default:
        Console.WriteLine("その他");
        break;
}

switch式

int day = 3;

string dayName = day switch
{
    1 => "月曜日",
    2 => "火曜日",
    3 => "水曜日",
    4 => "木曜日",
    5 => "金曜日",
    6 or 7 => "週末",
    _ => "不明"
};

Console.WriteLine(dayName);  // "水曜日"

パターンマッチング

object obj = "Hello";

// 型パターン
if (obj is string s)
{
    Console.WriteLine(s.ToUpper());
}

// switchでのパターンマッチング
string result = obj switch
{
    int i => $"整数: {i}",
    string s => $"文字列: {s}",
    null => "null",
    _ => "その他"
};

// プロパティパターン
record Person(string Name, int Age);

Person person = new("太郎", 25);

string category = person switch
{
    { Age: < 13 } => "子供",
    { Age: < 20 } => "ティーン",
    { Age: >= 65 } => "シニア",
    _ => "成人"
};

whenガード

int score = 85;

string grade = score switch
{
    >= 90 => "A",
    >= 80 => "B",
    >= 70 => "C",
    >= 60 => "D",
    _ => "F"
};

// 複雑な条件
string message = score switch
{
    100 => "満点!",
    >= 90 when score < 100 => "優秀",
    >= 80 => "良い",
    _ => "頑張りましょう"
};

ループ

for文

// 基本のfor文
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

// 逆順
for (int i = 4; i >= 0; i--)
{
    Console.WriteLine(i);
}

// ステップを変更
for (int i = 0; i < 10; i += 2)
{
    Console.WriteLine(i);  // 0, 2, 4, 6, 8
}

foreach文

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (int num in numbers)
{
    Console.WriteLine(num);
}

// 文字列
string text = "Hello";
foreach (char c in text)
{
    Console.WriteLine(c);
}

// ディクショナリ
var dict = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2
};

foreach (var (key, value) in dict)
{
    Console.WriteLine($"{key}: {value}");
}

while文

int count = 0;

while (count < 5)
{
    Console.WriteLine(count);
    count++;
}

do-while文

int count = 0;

do
{
    Console.WriteLine(count);
    count++;
} while (count < 5);

break と continue

// break - ループを抜ける
for (int i = 0; i < 10; i++)
{
    if (i == 5)
    {
        break;
    }
    Console.WriteLine(i);  // 0, 1, 2, 3, 4
}

// continue - 次の反復へ
for (int i = 0; i < 10; i++)
{
    if (i % 2 == 0)
    {
        continue;
    }
    Console.WriteLine(i);  // 1, 3, 5, 7, 9
}

LINQ での処理

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Where(フィルタ)
var evens = numbers.Where(n => n % 2 == 0);

// Select(変換)
var doubled = numbers.Select(n => n * 2);

// 複合処理
var result = numbers
    .Where(n => n % 2 == 0)
    .Select(n => n * 2)
    .ToList();

// First / FirstOrDefault
int first = numbers.First(n => n > 5);  // 6
int? notFound = numbers.FirstOrDefault(n => n > 100);  // 0

// Any / All
bool hasEven = numbers.Any(n => n % 2 == 0);  // true
bool allPositive = numbers.All(n => n > 0);   // true

// Sum / Average / Count
int sum = numbers.Sum();           // 55
double avg = numbers.Average();    // 5.5
int count = numbers.Count();       // 10

実践例:数当てゲーム

using System;

class NumberGame
{
    static void Main()
    {
        Random random = new();
        int answer = random.Next(1, 101);  // 1-100
        int attempts = 0;

        Console.WriteLine("1から100までの数を当ててください");

        while (true)
        {
            Console.Write("入力: ");
            if (!int.TryParse(Console.ReadLine(), out int guess))
            {
                Console.WriteLine("数字を入力してください");
                continue;
            }

            attempts++;

            switch (guess)
            {
                case var n when n < answer:
                    Console.WriteLine("もっと大きい");
                    break;
                case var n when n > answer:
                    Console.WriteLine("もっと小さい");
                    break;
                default:
                    Console.WriteLine($"正解! {attempts}回で当たりました");
                    return;
            }
        }
    }
}

まとめ

  • if/elseで条件分岐
  • switch式で値を返す分岐
  • パターンマッチングで型・プロパティによる分岐
  • ??/?.でnull安全な処理
  • for/foreach/whileでループ
  • LINQで宣言的なコレクション処理

次回はメソッドについて学びます。

広告エリア