Skip to content
On this page

循环结构之嵌套循环

在一个循环体中包含另一个循环,称为“嵌套循环”。当 2 个循环嵌套的时候,外层循环体执行一次,内层循环体执行 n 次(n 是内层循环的次数)。请看下面的例子:

img

运行结果:

img

比较代码和运行结果,我们发现,内层循环体执行 3 次,外层循环体执行 1 次。这就有点像钟表上的时针和分针——时针走一格,分针走一圈。

下面一段代码打印了一个矩形:

img

运行效果:

img

思考一下,哪一个变量决定了每一行的循环次数,x 还是 y?

任务 1

右边代码打印了一个矩形,请修改代码,使它打印三角形:

img

代码

csharp
using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int y = 1; y <= 7; y++) 
            {
                for (int x = 1; x <= 7; x++)
                {
                    if (x > y)
                        break;
                    Console.Write(x);
                }
                Console.WriteLine();//换行
            }
        }
    }
}
csharp
using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int y = 1; y <= 7; y++) 
            {
                for (int x = 1; x <= y; x++)
                {
                    Console.Write(x);
                }
                Console.WriteLine();//换行
            }
        }
    }
}

编程练习

嵌套循环至少包含 2 层循环,外层的循环体执行一次,内层的循环体则执行 n 次,内层体被执行的总次数 = 内层循环次数 * 外层循环次数。

任务 2

要输入如下图所示图形,请用嵌套的 for 循环实现。

img

代码

csharp
using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            // 请完善代码
            for (int x = 0; x < 7; ++x) {
                for (int y = 0; y < 7; ++y) {
                    if (x == y || x + y == 6) {
                        Console.Write("O");
                    } else {
                        Console.Write(".");
                    }
                }
                Console.WriteLine();
            }
        }
    }
}