C#では繰り返し処理を行うために、for、while、foreachの3種類のループ構文が用意されています。
それぞれ使い分けがあるため、基本的な使い方を押さえましょう。
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("回数: " + i);
}
}
}
for は回数が明確なときに使います。int i = 1:初期化、i <= 5:継続条件、i++:更新処理。using System;
class Program
{
static void Main()
{
int count = 1;
while (count <= 3)
{
Console.WriteLine("現在の値: " + count);
count++;
}
}
}
while は繰り返しの条件がある場合に使います。using System;
class Program
{
static void Main()
{
string[] fruits = { "りんご", "みかん", "バナナ" };
foreach (string fruit in fruits)
{
Console.WriteLine("果物: " + fruit);
}
}
}
foreach は配列やリストなどのコレクションを順番に処理するときに使います。fruit は各要素を受け取る変数で、in fruits が対象のコレクションです。
数値の配列 {1, 2, 3, 4, 5} を使って、次のように出力するプログラムをそれぞれのループ構文で書いてみましょう。