C#中的循环语句:do-while、while、for
其实还有个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
}
}
}
}
有好的建议,请在下方输入你的评论。
欢迎访问个人博客
https://guanchao.site
欢迎访问小程序: