循环就是重复执行一些语句来达到一定的目的,这个技术用起来很好,只要设定好参数,同样的代码可以执行成千上万次,.C#中的循环方法有几种:for, while,do-while 和for each.,在这里我们依次学习这些循环语句.
一. for循环
for(参数初始值;表达式是否成立;参数变化)
{
执行循环语句
}
先看个例子;循环计数器设为count;
string str = "编程bianceng"; //int x=1;for(;x<=7;x++),也可以写成这样 for (int x = 1; x <= 7; x++) { Console.WriteLine(str); } Console.ReadKey(); | 1编程bianceng 2编程bianceng 3编程bianceng 4编程bianceng 5编程bianceng 6编程bianceng 7编程bianceng | for(x的初始化;x是否满足条件;x递增或者递减) { 循环语句 } |
x控制循环次数,执行过程如下, 初始值是1,再判断x<=7是否成立 如果成立则输出(str);在x++; 到此第一次循环结束.然后又判断 x<=7.如果成立就执行循环语句, 当循环到x=8时,x <= 7不成立,循环结束了
同时也可以for循环可以写成其他的形式:
int xh=7; for (; xh >= 0; xh--) { Console.Write(xh); Console.WriteLine(str); } | 7编程bianceng 6编程bianceng 5编程bianceng 4编程bianceng 3编程bianceng 2编程bianceng 1编程bianceng 0编程bianceng | for循环中要注意的是防止死循环; 如果在循环过程中循环计数器没有发生改变就会不停的执行输出,直到 强制关闭控制台. |
二. while和do-while
while(计数器表达式) { Do something; 计数器变化 } | do { Do something;计数器变化 }while(表达式); |
其中两者的区别是do-while主要先执行一次在判断表达式是否成立,while循环是先看计数器表达式是否成立.若成立则执行循环,否则循环结束,计数器的变化和初始化很重要,如果在循环体中没有中断语句,跳出循环,否则是无穷循环..
下面先看两个例子:
int count = 1; while (count < 7) {// 计数表达式是否成立 Console.WriteLine("while count={0}", count); count++;//count的变化 }//count的值是7时(count < 7)不成立,循环结束 | count = 7; do { Console.WriteLine("do-while count={0}", count); count--; } while (count > 0); //当count=0时 (count > 0)不成立,循环结束,结束后count的值是0; |
while count=1 while count=2 while count=3 while count=4 while count=5 while count=6 | do--while count=7 do--while count=6 do--while count=5 do--while count=4 do--while count=3 do--while count=2 do--while count=1 |
三. foreach
其实foreach的实用方法是foreach( type1 op1 in type1集合)
先看个例子:
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 }; foreach (int i in fibarray) { System.Console.WriteLine(i); } 输出结果如右图: | foreach 0 1 2 3 5 8 13 |
string [] day=new string[]{"monday","turseday","wenseday","thursday","sunday","saturday"}; foreach (string str in day) { Console.WriteLine(str); } | monday turseday wenseday thursday sunday saturday |
到此循环语言的基本用法都介绍了,就剩下跳出循环的return,break,continue没有介绍了,在以后再介绍。