C# の入れ子ループをマスターする:For、while、および do-while について説明する
別のループ内のループは、ネストされたループと呼ばれます。ネストされたループは次のようになります。
Outer-Loop
{
// body of outer-loop
Inner-Loop
{
// body of inner-loop
}
... ... ...
}
ご覧のとおり外側のループです。 内側のループを囲みます。 。内側のループは外側のループの一部であり、外側のループの本体内で開始および終了する必要があります。
外側のループが反復されるたびに、内側のループが完全に実行されます。
ネストされた for ループ
別の for ループ内の for ループは、ネストされた for ループと呼ばれます。
例:
for (int i=0; i<5; i++)
{
// body of outer for loop
for (int j=0; j<5; j++)
{
// body of inner for loop
}
// body of outer for loop
}
例 1:ネストされた for ループ
using System;
namespace Loop
{
class NestedForLoop
{
public static void Main(string[] args)
{
int outerLoop = 0, innerLoop = 0;
for (int i=1; i<=5; i++)
{
outerLoop ++;
for (int j=1; j<=5; j++)
{
innerLoop++;
}
}
Console.WriteLine("Outer Loop runs {0} times", outerLoop);
Console.WriteLine("Inner Loop runs {0} times", innerLoop);
}
}
}
プログラムを実行すると、出力は次のようになります。
Outer Loop runs 5 times Inner Loop runs 25 times
このプログラムでは、外側のループが 5 回実行されます。外側のループが実行されるたびに、内側のループが 5 回実行され、合計 25 回実行されます。
例 2:ネストされた for ループからパターンを印刷する
using System;
namespace Loop
{
class NestedForLoop
{
public static void Main(string[] args)
{
for (int i=1; i<=5; i++)
{
for (int j=1; j<=i; j++)
{
Console.Write(j + " ");
}
Console.WriteLine();
}
}
}
}
プログラムを実行すると、出力は次のようになります。
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
ネストされた while ループ
別の while ループ内の while ループは、ネストされた while ループと呼ばれます。
例:
while (condition-1)
{
// body of outer while loop
while (condition-2)
{
// body of inner while loop
}
// body of outer while loop
}
例 3:ネストされた while ループ
using System;
namespace Loop
{
class NestedWhileLoop
{
public static void Main(string[] args)
{
int i=0;
while (i<2)
{
int j=0;
while (j<2)
{
Console.Write("({0},{1}) ", i,j);
j++;
}
i++;
Console.WriteLine();
}
}
}
}
プログラムを実行すると、出力は次のようになります。
(0,0) (0,1) (1,0) (1,1)
ネストされた do-while ループ
別の do-while ループ内の do-while ループは、ネストされた do-while ループと呼ばれます。
例:
do
{
// body of outer while loop
do
{
// body of inner while loop
} while (condition-2);
// body of outer while loop
} while (condition-1);
例 4:ネストされた do-while ループ
using System;
namespace Loop
{
class NestedWhileLoop
{
public static void Main(string[] args)
{
int i=0;
do
{
int j=0;
do
{
Console.Write("({0},{1}) ", i,j);
j++;
} while (j<2);
i++;
Console.WriteLine();
} while (i<2);
}
}
}
プログラムを実行すると、出力は次のようになります。
(0,0) (0,1) (1,0) (1,1)
異なる内側と外側のネストされたループ
同じタイプのループをネストすることは必須ではありません。 for ループを while ループ内に配置したり、do-while ループを for ループ内に配置したりできます。
例 5:C# ネストされたループ:異なる内部ループと外部ループ
using System;
namespace Loop
{
class NestedLoop
{
public static void Main(string[] args)
{
int i=1;
while (i<=5)
{
for (int j=1; j<=i; j++)
{
Console.Write(i + " ");
}
Console.WriteLine();
i++;
}
}
}
}
プログラムを実行すると、出力は次のようになります。
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
上記のプログラムでは、for ループが while ループ内に配置されています。ループ内でさまざまなタイプのループを使用できます。
C言語