C#中的循环结构


循环结构是程序中比较常用的一个结构,主要用来重复执行某一些代码从而达到预期的效果。
循环结构中主要包含四种格式,分别为:

*while循环
*do..while循环
*for循环
*foreach循环

while循环语句格式:

while(条件表达式)
{
循环体;
}

代码举例:

classWhileDemo
{
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

do..while循环语句格式:

do
{
循环体;
}
while(条件表达式);

注意和while的区别。

代码举例:
classWhileDemo
{
public static void Main(string[]args)
{
int a= 3;
do
{
a++;
System.Console.WriteLine("hello");
}
while(a < 3);
}
}

结果为1次hello


for循环语句格式:

for(初始化表达式; 条件表达式; 循环后的操作表达式)
{
循环体;
}

代码举例:

classWhileDemo
{
public static void Main(string[]args)
{
for(int a = 1; a < 3; a++)
{
System.Console.WriteLine("hello");
}
}
}

for循环中存在一种特殊的格式循环嵌套:

for(初始化表达式; 条件表达式; 循环后的操作表达式)
{
for(初始化表达式; 条件表达式; 循环后的操作表达式)
{
执行语句;
}
}

代码示例:

classForDemo
{
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
}
}


foreach循环语句格式:(后面学习)

foreach(数据类型 数据名 in 容器名)
{
执行语句;
}

需要注意的是foreach语句只能用来遍历。

break关键字

break,跳出,应用于循环结构和选择结构。作用是跳出所在的循环并终止所在循环。

classForDemo
{
public static void Main(string[]args)
{
for(int a = 1; a < 3; a++)
{
System.Console.WriteLine("hello");

if(a== 1)
{
break;
}
}
}
}

结果为打印1次hello

通常情况下,break要和其他语句结合使用,可以避免警告

classForDemo
{
public static void Main(string[]args)
{
for(int a = 1; a < 3; a++)
{
for(int b = 1; b < 4; b++)
{
System.Console.WriteLine("11111");
break;
}
}
}
}

break只会跳出它所在的循环

continue关键字

continue,继续,应用于循环结构。作用是结束本次循环继续执行下一次循环。

classWhileDemo
{
public static void Main(string[]args)
{
for(int a = 1; a <= 11; a++)
{
if(a% 2 == 0)
{
continue;
}
else
{
System.Console.WriteLine(a);
}
}
}
}


结果为打印出1~11之间所有的奇数

continue正常情况下和分支结构结合使用,一般不单独使用

注意,break和continue都是关键字,同时也都可以单独成句。如果这两个语句离开了应用范围将没有意义
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈言必行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值