温馨提示×

c# while循环如何嵌套使用

c#
小樊
87
2024-07-23 04:53:04
栏目: 编程语言

在C#中,可以嵌套使用while循环来实现多层循环。下面是一个示例代码,展示了如何使用嵌套的while循环:

using System;

class Program
{
    static void Main()
    {
        int outerCount = 0;
        while (outerCount < 3)
        {
            Console.WriteLine("Outer loop count: " + outerCount);

            int innerCount = 0;
            while (innerCount < 2)
            {
                Console.WriteLine("Inner loop count: " + innerCount);
                innerCount++;
            }

            outerCount++;
        }
    }
}

在上面的示例中,我们首先定义了一个外部循环outerCount,然后在外部循环中嵌套了一个内部循环innerCount。外部循环会执行3次,内部循环会在每次外部循环执行时执行2次,输出如下:

Outer loop count: 0
Inner loop count: 0
Inner loop count: 1
Outer loop count: 1
Inner loop count: 0
Inner loop count: 1
Outer loop count: 2
Inner loop count: 0
Inner loop count: 1

可以看到,嵌套的while循环可以帮助我们实现多层循环,以满足不同的需求。

0