如何在 C# 中为一维数组中指定位置的元素赋值

csharpprogrammingserver side programming更新于 2025/7/11 16:07:17

首先,设置数组为 −

int[] p = new int[] {55, 66, 88, 99, 111, 122, 133};

现在,假设您需要将位置 1 的元素赋值 −

p[2] = 77;

我们来看看完整的代码 −

示例

using System;

namespace Program {
   public class Demo {
      public static void Main(string[] args) {
         int[] p = new int[] {55, 66, 88, 99, 111, 122, 133};
         int j;

         Console.WriteLine("Initial Array......");
         for (j = 0; j < p.Length; j++ ) {
            Console.WriteLine("arr[j] = {0}", p[j]);
         }
         // set new element at index 2
         p[2] = 77;

         Console.WriteLine("New Array......");
         for (j = 0; j < p.Length; j++ ) {
            Console.WriteLine("arr[j] = {0}", p[j]);
         }
      }
   }
}

输出

Initial Array......
arr[j] = 55
arr[j] = 66
arr[j] = 88
arr[j] = 99
arr[j] = 111
arr[j] = 122
arr[j] = 133
New Array......
arr[j] = 55
arr[j] = 66
arr[j] = 77
arr[j] = 99
arr[j] = 111
arr[j] = 122
arr[j] = 133

相关文章