流程控制:循环结构
循环结构是程序中比较常用的一个结构,主要用来重复执行某一些代码从而达到预期的效果。
循环结构中主要包含四种格式,分别为:
* while循环
* do..while循环
* for循环
* foreach循环
1、while循环语句格式:
while(条件表达式)
{
}
代码举例:
class WhileDemo
{
public static void Main(string[] args)
{
int a = 1;
while(a < 3) //是否循环要看条件表达式的最后结果
{
System.Console.WriteLine("helloworld");
a++; //使用自增符号表示a的增量
}
System.Console.WriteLine("haha");
}
}
结果为2次hello world和1次haha
2、do..while循环语句格式:
do
{
}
while(条件表达式);
注意和while的区别。
代码举例:
class WhileDemo
{
public static void Main(string[] args)
{
int a = 3;
do
{
a++;
System.Console.WriteLine("hello");
}
while(a < 3);
}
}
结果为2次hello
3、for循环语句格式:
for(初始化表达式;条件表达式;循环后的操作表达式)
{
}
代码举例:
class WhileDemo
{
public static void Main(string[] args)
{
for(int a = 1; a < 3; a++)
{
System.Console.WriteLine("hello");
}
}
}
for循环中存在一种特殊的格式循环嵌套:
for(初始化表达式;条件表达式;循环后的操作表达式)
{
}
代码示例:
class ForDemo
{
public static void Main(string[] args)
{
for(int a = 1; a < 3; a++)
{
for(int b = 1; b < 4; b++)
{
System.Console.WriteLine("hello");
}
}
//结果是打印6个hello
}
}
break关键字
break,跳出,应用于循环结构和选择结构。作用是跳出所在的循环并终止所在循环。
class ForDemo
{
public static void Main(string[] args)
{
for(int a = 1; a < 3; a++)
{
System.Console.WriteLine("hello");
if(a == 1)
{
break;
}
}
}
}
结果为打印1次hello
通常情况下,break要和其他语句结合使用,可以避免警告
break只会跳出它所在的循环
continue关键字
continue,继续,应用于循环结构。作用是结束本次循环继续执行下一次循环。
class WhileDemo
{
public static voidMain(string[] args)
{
for(inta = 1; a <= 11; a++)
{
if(a% 2 == 0)
{
continue;
}
else
{
System.Console.WriteLine(a);
}
}
}
}
结果为打印出1~11之间所有的奇数
continue正常情况下和分支结构结合使用,一般不单独使用
注意,break和continue都是关键字,同时也都可以单独成句。如果这两个语句离开了应用范围将没有意义
由于小编对foreach循环不熟,本文中没有对foreach循环的介绍。如果喜欢本文章就收藏关注一下小编吧。。谢谢支持!