
一维数组是最简单的数组形式,它存储了一行数据。
// 声明并初始化一个包含5个整数的数组int[] numbers = new int[5];// 或者在声明时直接初始化数组元素int[] numbers2 = { 1, 2, 3, 4, 5 };// 访问数组元素int secondNumber = numbers2[1]; // 访问索引为1的元素,即2
多维数组用于存储多个维度的数据,如二维数组(矩阵)、三维数组等。
// 声明并初始化一个2x3的二维数组int[,] matrix = new int[2, 3];// 或者在声明时直接初始化二维数组元素int[,] matrix2 = {{1, 2, 3},{4, 5, 6}};// 访问二维数组元素int element = matrix2[0, 1]; // 访问第一行第二列的元素,即2
datatype[] arrayName;double[] balance; //定义了一个浮点类型的名称为balance的一维数组double[] balance = new double[10];balance,所有元素的初始值为该数据类型的默认值。double[] balance = new double[10];balance[0] = 4500.0;
double[] balance = { 2340.0, 4523.69, 3421.0};int [] marks = new int[5] { 99, 98, 92, 97, 95};int [] marks = new int[] { 99, 98, 92, 97, 95};int [] marks = new int[] { 99, 98, 92, 97, 95};int[] score = marks;
int[] arr = { 1, 2, 3, 4 };// 按索引读取int element = arr[2]; // 获取索引2的值(3)// 遍历查询foreach (int num in arr){Console.WriteLine(num);}
arr[1] = 99; // 将索引1的值改为99 → {1,99,3,4}int indexToDelete = 1; // 删除索引1的元素int[] newArr = new int[arr.Length - 1];int currentIndex = 0;for (int i = 0; i < arr.Length; i++){if (i != indexToDelete){newArr[currentIndex] = arr[i];currentIndex++;}}// 结果:{1,3,4}
int newValue = 10;int[] newArr = new int[arr.Length + 1];// 复制原数组for (int i = 0; i < arr.Length; i++){newArr[i] = arr[i];}// 末尾添加新元素newArr[newArr.Length - 1] = newValue;// 结果:{1,2,3,4,10}
double salary = balance[9];//一维数组的访问,下标为9的元素,也就是第十位元素double salary = balance[2,2];//二维数组的访问using System;namespace ArrayApplication{class MyArray{staticvoidMain(string[] args){int [] n = new int[10]; /* n 是一个带有 10 个整数的数组 */int i,j;/* 初始化数组 n 中的元素 */for ( i = 0; i < 10; i++ ){n[ i ] = i + 100;}/* 输出每个数组元素的值 */for (j = 0; j < 10; j++ ){Console.WriteLine("Element[{0}] = {1}", j, n[j]);}Console.ReadKey();}}}
Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105Element[6] = 106Element[7] = 107Element[8] = 108Element[9] = 109
using System;namespace ArrayApplication{class MyArray{staticvoidMain(string[] args){int [] n = new int[10]; /* n 是一个带有 10 个整数的数组 *//* 初始化数组 n 中的元素 */for ( int i = 0; i < 10; i++ ){n[i] = i + 100;}/* 输出每个数组元素的值 */foreach (int j in n ){int i = j-100;Console.WriteLine("Element[{0}] = {1}", i, j);}Console.ReadKey();}}}
Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105Element[6] = 106Element[7] = 107Element[8] = 108Element[9] = 109