C#: C# の例
1. FizzBuzz
1から100まで繰り返し処理を行い、3の倍数には「Fizz」、5の倍数には「Buzz」、3と5の両方の倍数には「FizzBuzz」と出力し、それ以外の場合はその数自体を出力する。
▶ サンプル
CSHARP
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 100; i++)
{
if (i % 15 == 0)
Console.WriteLine("FizzBuzz");
else if (i % 3 == 0)
Console.WriteLine("Fizz");
else if (i % 5 == 0)
Console.WriteLine("Buzz");
else
Console.WriteLine(i);
}
}
}
TEXT
📖 参照専用
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
...
98
Fizz
Buzz
2. フィボナッチ数列
フィボナッチ数列の最初の20個の数を表示してください。各数は、その前の2つの数の和です。
▶ サンプル
CSHARP
using System;
class Program
{
static void Main()
{
int a = 0, b = 1;
for (int i = 0; i < 20; i++)
{
Console.Write(a + " ");
int temp = a;
a = b;
b = temp + b;
}
Console.WriteLine();
}
}
TEXT
📖 参照専用
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
3. 九九
三角形の配置で、定番の九九を印刷してください。
▶ サンプル
CSHARP
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write($"{j}x{i}={i * j}\t");
}
Console.WriteLine();
}
}
}
TEXT
📖 参照専用
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
4. プライムチェック
ユーザーが入力した正の整数が素数であるかどうかを判定し、その結果を出力してください。
▶ サンプル
CSHARP
using System;
class Program
{
static bool IsPrime(int n)
{
if (n < 2) return false;
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0) return false;
}
return true;
}
static void Main()
{
int number = 29;
if (IsPrime(number))
Console.WriteLine($"{number} is prime");
else
Console.WriteLine($"{number} is not prime");
number = 35;
if (IsPrime(number))
Console.WriteLine($"{number} is prime");
else
Console.WriteLine($"{number} is not prime");
}
}
TEXT
📖 参照専用
29 is prime
35 is not prime
5. 回文の検出
ある文字列が回文(前後から読んでも同じになる文字列)であるかどうかを判定する。
▶ サンプル
CSHARP
using System;
class Program
{
static bool IsPalindrome(string s)
{
int left = 0, right = s.Length - 1;
while (left < right)
{
if (s[left] != s[right]) return false;
left++;
right--;
}
return true;
}
static void Main()
{
string[] tests = { "racecar", "hello", "level", "world" };
foreach (string t in tests)
{
Console.WriteLine($"{t} -> {(IsPalindrome(t) ? "is palindrome" : "is not palindrome")}");
}
}
}
TEXT
📖 参照専用
racecar -> is palindrome
hello -> is not palindrome
level -> is palindrome
world -> is not palindrome
6. 文字列の逆順化
入力文字列を逆順にして、その結果を出力します。
▶ サンプル
CSHARP
using System;
class Program
{
static string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
static void Main()
{
string original = "Hello CSharp";
string reversed = ReverseString(original);
Console.WriteLine($"Original: {original}");
Console.WriteLine($"Reversed: {reversed}");
}
}
TEXT
📖 参照専用
Original: Hello CSharp
Reversed: prahSC olleH
7. 母音を数える
文字列中の母音(a, e, i, o, u、大文字小文字を区別しない)の出現回数を数えます。
▶ サンプル
CSHARP
using System;
class Program
{
static int CountVowels(string s)
{
int count = 0;
string vowels = "aeiouAEIOU";
foreach (char c in s)
{
if (vowels.IndexOf(c) >= 0)
count++;
}
return count;
}
static void Main()
{
string text = "Hello World Programming";
int result = CountVowels(text);
Console.WriteLine($"String: {text}");
Console.WriteLine($"Vowel count: {result}");
}
}
TEXT
📖 参照専用
String: Hello World Programming
Vowel count: 6
8. ファイル入出力
テキストファイルの基本的な書き込みおよび読み取り操作を実演する。
▶ サンプル
CSHARP
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "test.txt";
string[] lines = { "First line", "Second line", "Third line" };
File.WriteAllLines(path, lines);
Console.WriteLine("Write complete");
string[] readLines = File.ReadAllLines(path);
Console.WriteLine("Read content:");
foreach (string line in readLines)
{
Console.WriteLine(line);
}
File.Delete(path);
}
}
TEXT
📖 参照専用
Write complete
Read content:
First line
Second line
Third line
9. 数字当てゲーム
このプログラムは、1から100までの間のランダムな整数を生成します。プレイヤーが数字を当てていき、正解が見つかるまで、プログラムはその数字が「高すぎる」か「低すぎる」かをヒントとして示します。
▶ サンプル
CSHARP
using System;
class Program
{
static void Main()
{
Random rnd = new Random(42);
int target = rnd.Next(1, 101);
int[] guesses = { 50, 75, 62, 68, 71, 73, 72 };
int attempts = 0;
Console.WriteLine($"Target number: {target} (shown for demo only)");
Console.WriteLine("---");
foreach (int guess in guesses)
{
attempts++;
if (guess < target)
Console.WriteLine($"Attempt {attempts}: {guess} - Too low");
else if (guess > target)
Console.WriteLine($"Attempt {attempts}: {guess} - Too high");
else
{
Console.WriteLine($"Attempt {attempts}: {guess} - Correct!");
break;
}
}
}
}
TEXT
📖 参照専用
Target number: 72 (shown for demo only)
---
Attempt 1: 50 - Too low
Attempt 2: 75 - Too high
Attempt 3: 62 - Too low
Attempt 4: 68 - Too low
Attempt 5: 71 - Too low
Attempt 6: 73 - Too high
Attempt 7: 72 - Correct!
10. 学生の成績計算ツール
ある生徒の成績の集合が与えられたとき、平均点、最高点、最低点を求めなさい。
▶ サンプル
CSHARP
using System;
using System.Linq;
class Program
{
static void Main()
{
double[] scores = { 85.5, 92.0, 78.5, 96.0, 88.0, 73.5, 91.0 };
double average = scores.Average();
double max = scores.Max();
double min = scores.Min();
Console.WriteLine("Student grades: " + string.Join(", ", scores));
Console.WriteLine($"Average: {average:F1}");
Console.WriteLine($"Highest: {max:F1}");
Console.WriteLine($"Lowest: {min:F1}");
}
}
TEXT
📖 参照専用
Student grades: 85.5, 92, 78.5, 96, 88, 73.5, 91
Average: 86.4
Highest: 96.0
Lowest: 73.5
❓ よくある質問
Q これらのC#のサンプルコードを実行するにはどうすればよいですか?
A コードを.csファイルにコピーして「dotnet run」で実行するか、dotnetfiddle.netなどのオンラインC#コンパイラを使用してください。
Q サンプルコードを修正して、結果を確認することはできますか?
A はい!ファイルを保存して、もう一度
dotnet run を実行してください。C# はバイトコードにコンパイルされるため、変更は即座に反映されます。Q もっと大規模な例はどこにありますか?
A 第36課「最終プロジェクト」をご覧ください。このインデックスには、1つの概念に絞った短いスニペットのみを掲載しています。
📖 まとめ
- 各例は独立したコードとなっています。任意の C# 環境でコピーして実行できます。
- 例題は、一度に一つの概念に焦点を当てています
- 自由に変更して、その挙動を調べてみてください
- 大規模なプロジェクトについては、専用のレッスンをご覧ください
📝 練習問題
- 任意の例を選び、それを変更し、新しい動作をコメントで記録してください。
- 2つの例(例:変数とイベント)を1つのプログラムにまとめる。
- 自分が分かりにくいと感じる概念を解説する、独自のサンプルページを作成してください。