for

For循环

 语句:顺序,分支,循环

 循环:反复执行某一段代码

 循环四要素:初始条件循环条件循环体状态改变

 

格式:

            for (int i = 1/*初始条件*/; i <= 100/* 循环条件*/; i++ /*状态改变*/)

            {

                //循环体,执行代码;(break;跳出循环体)

            }

从给出的初始条件判断是否满足循环条件,若满足进入循环体,执行代码,跳出花括号,状态改变——变量改变,判断是否还满足循环条件,若满足继续执行循环体,直至不满足循环条件为之,或者碰到break;命令,直接跳出当前的for循环。若一开始不满足则不进入循环体。

            

     例 :  输入一个整数,计算从1加到这个数的结果

            Console.Write("请输入一个正整数:");

            int a = int.Parse(Console.ReadLine());

            int sum = 0;

            for (int i = 1; i <= a; i++)

            {

                //sum = sum + i;

                sum += i;

            }

            Console.WriteLine("累加求和的结果为:"+sum);

            Console.ReadLine();

 

 

            死循环:出不来,一直在执行 只要没有循环条件就是死循环

            for (; ; )

            {

                Console.WriteLine("你好");

            }

            //i==10的时候跳出

 

            for ( int i = 0; ;  i++)

            {

                if (i == 10)

                {

                    break;//跳出整个循环

                }

            }

三角形

for嵌套

//左上
            for (int i = 5; i >= 1; i--)
            {
                for (int j = 1; j <= i; j++)
                {
                    Console.Write("□");
                }
                Console.Write("\n");
            }
            Console.ReadLine();

//左下
            for (int i = 1; i <= 5; i++)
            {
                for (int j = 1; j <= i; j++)
                {
                    Console.Write("□");
                }
                Console.Write("\n");
            }
            Console.ReadLine();

//右上
            for (int i = 1; i <= 5; i++)
            {
                for (int j = 1; j < i; j++)
                {
                    Console.Write("●");
                }
                for (int k = 6 - i; k >= 1; k--)
                {
                    Console.Write("□");
                }
                Console.Write("\n");
            }
            Console.ReadLine();

//右下
            for (int i = 1; i <= 5; i++)
            {
                for (int j = 1; j <= 5 - i; j++)
                {
                    Console.Write("  ");
                }
                for (int k = 1; k <= i; k++)
                {
                    Console.Write("□");
                }
                Console.Write("\n");
            }
            Console.ReadLine();

 

posted @ 2016-06-22 22:36  无毒不羁  阅读(328)  评论(0编辑  收藏  举报