C#•ループ
C# の while と do-while ループ(例題付き)
反復回数が外部条件やキューの状態に依存する場合に while ループを使用します。
構文
while (condition) {}
do {} while (condition);
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| while | Loop | 本体を実行する前に条件を判定します。 |
そのまま実行できるコード例
Compilra で実行可能C# をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
using System;
public class Program {
public static void Main() {
int countdown = 3;
Console.WriteLine("--- Countdown ---");
while (countdown > 0) {
Console.WriteLine($"T-minus {countdown}...");
countdown--;
}
Console.WriteLine("Liftoff! 🚀\n");
int attempts = 0;
do {
attempts++;
Console.WriteLine($"Execution count (runs at least once): {attempts}");
} while (attempts < 1);
}
}期待される出力:
--- Countdown --- T-minus 3... T-minus 2... T-minus 1... Liftoff! 🚀 Execution count (runs at least once): 1
動作のしくみ: ステップ解説
- 6-9 行目: while ループが 3 から 0 までカウントダウンします。
- 13-16 行目: do-while は条件評価の前にブロックを 1 回実行します。
重要ポイント
- while は最初に条件を確認するため、初回から偽なら実行されません。
- do-while は少なくとも 1 回本体を実行します。
よくある間違い: カウンターのデクリメントを忘れて無限ループになる
条件変数を更新し忘れるとスレッドが停止します。
❌ 誤り
while (c > 0) { Console.WriteLine(c); } // Infinite loop!✅ 正しい例
while (c > 0) { Console.WriteLine(c); c--; }関連するC#チュートリアルとコンパイラ
C# の foreach によるジェネリック List コレクション反復の仕組み
IEnumerable<T> 列挙子の状態や読み取り専用カーソルの安全性を理解しつつ、C# の foreach による List<T> 走査を習得しましょう。
C# のループにおける break 文と continue 文
C# で break と continue を使ってループ反復を中断したりスキップしたりしましょう。
C# のパターンマッチング switch 文と switch 式
関係範囲、論理コンビネータ (and/or)、破棄ガードを備えたモダンな C# パターンマッチング switch 式 (=>) を実装します。
C# オンラインコンパイラ
Compilra IDE で開く