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
相关推荐
结衣结衣.5 分钟前
python中的函数介绍
java·c语言·开发语言·前端·笔记·python·学习
茫茫人海一粒沙8 分钟前
Python 代码编写规范
开发语言·python
原野心存9 分钟前
java基础进阶知识点汇总(1)
java·开发语言
程序猿阿伟11 分钟前
《C++高效图形用户界面(GUI)开发:探索与实践》
开发语言·c++
暗恋 懒羊羊19 分钟前
Linux 生产者消费者模型
linux·开发语言·ubuntu
五味香35 分钟前
C++学习,信号处理
android·c语言·开发语言·c++·学习·算法·信号处理
梓䈑1 小时前
【C语言】自定义类型:结构体
c语言·开发语言·windows
鱼跃鹰飞1 小时前
Leecode热题100-295.数据流中的中位数
java·服务器·开发语言·前端·算法·leetcode·面试
小蜗笔记1 小时前
在Python中实现多目标优化问题(7)模拟退火算法的调用
开发语言·python·模拟退火算法