using System;
public class Program
{
public static void Main(string[] args)
{
int count = 1;
while (count <= 3)
{
// countが3以下である間、ループを繰り返す
Console.WriteLine("ネコが" + count + "匹います");
count++;// countを1増やす (インクリメント)
}
}
}
出力結果
ネコが1匹います
ネコが2匹います
ネコが3匹います
次のコード例では、条件が満たされなくなるまで処理を続ける様子を確認できます。
using System;
public class Program
{
public static void Main(string[] args)
{
int energy = 5; // 体力の初期値
// energyが0より大きい間、ループを繰り返す
while (energy > 0)
{
Console.WriteLine("イヌが走っています(体力:" + energy + ")");
energy -= 2;
}
Console.WriteLine("イヌが疲れて止まりました");
}
}
using System;
public class Program
{
public static void Main(string[] args)
{
int rabbit_count = 1; // ジャンプするウサギの初期値
// rabbit_countが4以下の間、ループを繰り返す
while (rabbit_count <= 4)
{
// 現在のウサギの番号を出力
Console.WriteLine(rabbit_count + "番目のウサギが跳んでいます");
rabbit_count++;
}
}
}
using System;
public class Program
{
public static void Main(string[] args)
{
// 文字列の配列を初期化
string[] animals = {"ライオン", "トラ", "ヒョウ"};
int index = 0; // 配列のインデックス(添え字)を0で初期化
while (index < animals.Length)
{
Console.WriteLine("動物園にいる動物: " + animals[index]);
index++;
}
}
}
using System;
using System.Collections.Generic; // List<T>を使用するために必要
public class Program
{
public static void Main(string[] args)
{
var zoo_animals = new List<string> {"パンダ", "キリン", "シマウマ"};
int animal_index = 0;
// animal_indexがリストの要素数未満である間、ループを繰り返す
while (animal_index < zoo_animals.Count)
{
Console.WriteLine("見学中: " + zoo_animals[animal_index]);
animal_index++;
}
Console.WriteLine("動物の見学が完了しました。");
}
}