C#循环语句总结

前言

正所谓磨刀不误砍柴工,C#上位机软件开发能力的提升离不开对C#语法的精通,本文接着讲解C#语法知识中的循环语句,在C#程序开发中我们经常会用到各种循环语句,常见的有for循环、while循环,本文就是对C#中用到的各种循环语句进行了总结,内容如下:

1、for循环

1.1 每次加1递增循环

每次增加1,循环10次

复制代码
    for(int i=0;i<10;i++)
    {
        Console.WriteLine(i);
    }

输出:

csharp 复制代码
0
1
2
3
4
5
6
7
8
9

1.2 设置指定步长的递增循环

每次增加2,可设置步长,循环5次

csharp 复制代码
 int stepAdd = 2;
        for (int i = 0; i < 10; i=i+ stepAdd)
        {
            Console.WriteLine(i);
        }

输出:

csharp 复制代码
0
2
4
6
8

1.3 递减循环

每次减2,可设置步长,循环5次

复制代码
int stepDec = 2;
    for (int i = 10; i >0; i = i - stepDec)
    {
        Console.WriteLine(i);
    }

输出:

csharp 复制代码
10
8
6
4
2

2、while循环

2.1 搭配break语句跳出循环

break语句执行时,直接跳出while循环。

csharp 复制代码
  int count = 0;
        while (true )
        {
            count = count + 1;
            Console.WriteLine(count);
            if (count >=10)
            {
                break;//使用break跳出大的循环语句
            }
        }

输出:

csharp 复制代码
1
2
3
4
5
6
7
8
9
10

2.2 搭配continue语句不执行当前循环后面语句

continue执行时,continue语句后面的代码都不执行,然后会重新跳到 while (true)这里。

从输出结果可以看出count等于5的时候没有输出

复制代码
count = 0;
    while (true)
    {
        count = count + 1;
        if (count == 5)
        {
            continue;//使用continue不执行本次循环后面的语句
        }

        if (count >= 10)
        {
            break;//使用break跳出大的循环语句
        }
        Console.WriteLine(count);
    }

输出:

csharp 复制代码
1
2
3
4
6
7
8
9

3、do while循环

do while循环,先执行语句,然后判断是否继续执行循环

下面的代码中count < 10就执行循环,否则结束循环

csharp 复制代码
   count = 0;
        do
        {
            count = count + 1;
            Console.WriteLine(count);
        }
        while (count < 10);

输出:

csharp 复制代码
1
2
3
4
5
6
7
8
9
10

4、foreach循环

foreach循环,一般用于对集合对象的访问

csharp 复制代码
   List<int> ListTest = new List<int>();
        ListTest.Add(1);
        ListTest.Add(2);
        ListTest.Add(3);
        ListTest.Add(4);
        ListTest.Add(5);
        foreach (int item in ListTest)
        {
            Console.WriteLine(item);
        }

输出:

csharp 复制代码
1
2
3
4
5
相关推荐
向阳@向远方21 分钟前
第二章 简单程序设计
开发语言·c++·算法
Mr_Xuhhh1 小时前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构
纳兰青华1 小时前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list
好开心啊没烦恼1 小时前
Python 数据分析:DataFrame,生成,用字典创建 DataFrame ,键值对数量不一样怎么办?
开发语言·python·数据挖掘·数据分析
liulilittle1 小时前
VGW 虚拟网关用户手册 (PPP PRIVATE NETWORK 基础设施)
开发语言·网络·c++·网关·智能路由器·路由器·通信
Devil枫1 小时前
Kotlin高级特性深度解析
android·开发语言·kotlin
ChinaDragonDreamer1 小时前
Kotlin:2.1.20 的新特性
android·开发语言·kotlin
安之若素^2 小时前
启用不安全的HTTP方法
java·开发语言
一个天蝎座 白勺 程序猿2 小时前
Python(28)Python循环语句指南:从语法糖到CPython字节码的底层探秘
开发语言·python
持梦远方2 小时前
C 语言基础入门:基本数据类型与运算符详解
c语言·开发语言·c++