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 循环内。我们可以在循环内使用不同类型的循环。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战