How to set a value to the element at the specified position in the one-dimensional array in C#

CsharpProgrammingServer Side Programming

Firstly, set the array −

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

Now, let us say you need to set an element at position 1 −

p[2] = 77;

Let us see the comple code −

Example

 Live Demo

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]);
         }
      }
   }
}

Output

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
raja
Updated on 22-Jun-2020 13:05:58

Advertisements