温馨提示×

c#中for循环如何遍历数组

c#
小樊
81
2024-09-20 06:20:58
栏目: 编程语言

在C#中,你可以使用for循环或者foreach循环来遍历数组。下面是两种方法的示例:

  1. 使用for循环遍历数组:
int[] array = new int[] { 1, 2, 3, 4, 5 };

for (int i = 0; i < array.Length; i++)
{
    Console.WriteLine("Element at index " + i + ": " + array[i]);
}
  1. 使用foreach循环遍历数组:
int[] array = new int[] { 1, 2, 3, 4, 5 };

foreach (int element in array)
{
    Console.WriteLine("Element: " + element);
}

在这两个示例中,我们都遍历了一个整数数组,并打印出了每个元素。for循环使用索引来访问数组的元素,而foreach循环则直接访问数组的元素。

0