C# for和 foreach 的数组遍历 比较

时间:2025-03-08 21:37:02

刚学习程序,感觉写代码 很有意思,所以把自己的感悟写下来啦,第一次写博客,可能是菜鸟中的菜鸟  时间久了,相信就会写的很好哦!

for和 foreach 的数组遍历 比较

很简单的程序,不解释啦!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{ int[] nums = { 3, 5, 99, 23, 53, 88 }; //定义数组
int max = 0; for (int i = 0; i < nums.Length; i++) //for遍历数组
{
if (nums[i] > max)
{
max = nums[i];
}
}
Console.WriteLine("for遍历数组demo:" + max);
Console.WriteLine("====================================================");
foreach (var p in nums) //使用foreach 遍历
{
if (p > max)
{
max = p;
} }
Console.WriteLine("foreach遍历数组demo:"+max); } }
}

   结果为:

C# for和 foreach 的数组遍历 比较