码迷,mamicode.com
首页 > 其他好文 > 详细

for

时间:2016-06-22 23:39:02      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

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();

 

for

标签:

原文地址:http://www.cnblogs.com/ShenG1/p/5608867.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!