Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách gán giá trị cho phần tử tại vị trí chỉ định trong mảng một chiều C#

Đầu tiên, thiết lập mảng:

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

Bây giờ, giả sử bạn cần thiết lập phần tử tại vị trí 1 (chỉ số 2):

p[2] = 77;

Hãy xem mã hoàn chỉnh:

Ví dụ

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

Kết quả

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