如何在 C# 中使用“for 循环”访问数组元素?


‘for 循环’多次执行一系列语句并缩短了管理循环变量的代码。

以下是我们的 for 循环。

示例

 在线演示

using System;
namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int [] n = new int[10]; /* n is an array of 10 integers */
         int i,j;
         /* initialize elements of array n */
         for ( i = 0; i < 10; i++ ) {
            n[ i ] = i + 100;
         }
         /* output each array element's value */
         for (j = 0; j < 10; j++ ) {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         int a = n[2];
         Console.WriteLine(a);
         Console.ReadKey();
      }
   }
}

输出

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
102

现在假设你需要第三个元素。为此,请使用。

int a = n[1];

上述代码将给出第三个元素,即 102。

更新于:2020 年 6 月 23 日

246 次浏览

开启您的 职业生涯

完成课程以获得认证

立即开始
广告
© . All rights reserved.