十八、流程控制之循环中断

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _18.流程控制之循环中断
{
    class Program
    {
        static void Main(string[] args)
        {
            /**
             * 循环的中断方式有四种:
             * (1) break语句立即终止当前所在的循环。
             * (2) continue语句立即终止本次循环,继续执行下一次循环。
             * (3) goto语句可以跳出循环,到已标记好的位置上。
             * (4) return语句跳出循环及其包含的函数。
             * 
             */
             
            // 使用break语句中断循环
            {
                int i = 1;
                
                while (i <= 10)
                {
                    if (i == 6)
                        break;
                    Console.WriteLine("{0}", i++);
                }
            }
            
            // 使用continue语句中断循环
            {
                int i;
                
                for (i = 1; i <= 10; i++)
                {
                    if ((i % 2) == 0)
                        continue;
                    Console.WriteLine(i);
                }
            }
            
            // 使用goto语句中断循环
            // 当使用goto语句跳出循环是合法的,但使用goto语句从外部进入循环是非法的。
            {
                int i = 1;
                
                while (i < 10)
                {
                    if (i == 6)
                        goto exitPoint;
                    Console.WriteLine("{0}", i++);
                }
                
                Console.WriteLine("This code will never be reached.");
                
            exitPoint:
                Console.WriteLine("This code is run when the loop is exited using goto.");
            }
            
            // 使用return语句中断循环
            {
                int i = 0;
                
                do
                {
                    if (i == 6)
                        return;
                    Console.WriteLine("{0}", i++);
                } while (i < 10);
            }
            
            Console.ReadKey();
        }
    }
}