C#(九)之循环语句for while do-while break continue

博客主要介绍了C#中的循环语句,包括for、while、do - while,提到foreach待学习数组后补充。还介绍了for实现死循环、do - while至少执行一次循环,以及break、continue的作用,指出C#循环逻辑可参照PHP,并给出测试代码使用控制台程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

欢迎访问小程序:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值