「这是我参与2022首次更文挑战的第10天,活动详情查看:2022首次更文挑战」
C#中的循环语句:do-while、while、for
循环:反复执行某段代码。
循环四要素:初始条件,循环条件,循环体,状态改变。
for(初始条件;循环条件;状态改变)
{
循环体
}
给出初始条件,先判断是否满足循环条件,如果不满足条件则跳过for语句,如果满足则进入for语句执行,for语句内的代码执行完毕后,将按照状态改变,改变变量,然后判断是否否和循环条件,符合则继续执行for语句内的代码,直到变量i不符合循环条件则终止循环,或者碰到break命令,直接跳出当前的for循环。
break ——中断循环,跳出最近的循环循环
continue——停止本次循环,进入下次循环
循环(for)和分支语句(if else等)一样可以相互嵌套
其实还有个foreach,这个等看完数组之后再补充吧
1:for循环
int a = 10;
for (int i = 0; i <= a; i++ ){
Console.WriteLine(i);
}
//输出结果:0 1 2 3 4 5 6 7 8 9 10
使用for实现死循环
for (; ; )
{
a++;
Console.WriteLine(a);
}
2:while
int i = 0;
while(i <= a){
Console.WriteLine(i);
i++;
}
//输出结果:0 1 2 3 4 5 6 7 8 9 10
3:do-while,不管判断条件是否成立,循环至少被执行一次
//int i = 0;//输出结果:1 2 3 4 5 6 7 8 9 10 11
int i = 11; // 输出结果12
do
{
i++;
Console.WriteLine(i);
} while (i <= a);
4:break、continue
Break:强制跳出循环。
// break
int aa = 0;
for (int i = 0; i <= 10;i++ )
{
if(i >= 5){
break;
}
aa++;
Console.WriteLine(aa); // 输出1 2 3 4 5
}
Continue:跳出本次循环,执行下一次循环。
//continue
int bb = 0;
for (int j = 0; j < 5;j++ )
{
if (j == 5 || j == 1 || j == 3 )
{
continue;
}
Console.WriteLine(j); // 输出0 2 4
}
实践出真知,结果就是C#中以上三种循环的逻辑可以参照PHP。
测试使用代码:我这里使用的是控制台程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gc
{
class Program
{
/* C#主要的运行函数,就是main函数 */
static void Main(string[] args)
{
int a = 10;
/*for (int i = 0; i <= a; i++ ){
Console.WriteLine(i);
}//*/
//输出结果:0 1 2 3 4 5 6 7 8 9 10
/*for (; ; )
{
a++;
Console.WriteLine(a);
}//*/
/*int i = 0;
while(i <= a){
Console.WriteLine(i);
i++;
}
//输出结果:0 1 2 3 4 5 6 7 8 9 10//*/
//int i = 0;//输出结果:1 2 3 4 5 6 7 8 9 10 11
/*int i = 11; // 输出结果12
do
{
i++;
Console.WriteLine(i);
} while (i <= a);//*/
// break
/* int aa = 0;
for (int i = 0; i <= 10;i++ )
{
if(i >= 5){
break;
}
aa++;
Console.WriteLine(aa); // 输出1 2 3 4 5
}//*/
//continue
int bb = 0;
for (int j = 0; j < 5;j++ )
{
if (j == 5 || j == 1 || j == 3 )
{
continue;
}
Console.WriteLine(j); // 输出0 2 4
}
}
}
}
有好的建议,请在下方输入你的评论。
欢迎访问个人博客 guanchao.site
欢迎访问小程序: