软件编程
位置:首页>> 软件编程>> C#编程>> C#中循环语句:while、for、foreach的使用

C#中循环语句:while、for、foreach的使用

作者:自由自在的虫子  发布时间:2022-05-01 02:42:55 

标签:C#,循环,while,for,foreach

循环结构可以实现一个程序模块的重复执行,它对于我们简化程序,更好地组织算法有着重要的意义。C#为我们提供了若干种循环语句,分别适用于不同的情形,下面依次介绍。

C#中循环语句:while、for、foreach
1、while循环


static void Main(string[] args)
{
int[] hs = { 1,2,3,4,5,6,7,8,9};
int ligh = hs.Length;
while (ligh > 0)
{
 Console.WriteLine(hs[ligh - 1]);
 ligh -= 1;
}
 Console.ReadKey();
}


 2、for循环(可以嵌套for循环,比如:做冒泡排序的时候会用到)


static void Main(string[] args)
{
int[] hs = { 1,2,3,4,5,6,7,8,9};
//倒叙打印只需要修改一下判断条件即可
for (int i = 0; i < hs.Length; i++)
{
 Console.WriteLine(hs[i].ToString());
}
 Console.ReadKey();
}


 3、foreach循环遍历集合中的元素(这种写法貌似是.NET独有的吧)


static void Main(string[] args)
{
int[] hs = { 1,2,3,4,5,6,7,8,9};
//这里用到了var关键字,匿名类型(由编译器自动推断),你可以把它换成int
foreach (var item in hs)
{
 Console.WriteLine(item.ToString());
}
Console.ReadKey();
}

通过以上具体实例的介绍,希望可以给大家有所启迪,帮助大家很好的理解与运用循环语句。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com