数组用于保存一组数据。
数组的特点:
- 数组长度必须固定。
- 数组中每个元素的数据类型必须一致。
- 数组元素通过下标来访问,下标从0开始。
一、一维数组
数组的声明:
int[] arr;
数组的定义:
int[] arr;
arr = new int[5];
数组的声明+定义:
int[] arr = new int[5];
通过下标给数组赋值:
int[] arr = new int[5];
arr[0] = 100;
arr[1] = 80;
arr[2] = 70;
arr[3] = 60;
arr[4] = 50;
数组的初始化:
int[] arr = {85,98,75,84,56,87};
或
int[] arr = new int[]{85,98,75,84,56,87};
或
int[] arr = new int[5]{85,98,75,84,56,87};
通过循环进行数组的输出:
int[] arr = new int[]{85,98,75,84,56,87,75};
for (int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
}
二、二维数组
多维数组可以看成是数组的数组,比如二维数组就是一个特殊的一维数组,其每一个元素都是一个一维数组 。
二维数组也可以理解成具有行和列的矩阵。
例如:(以下代码即定义了一个3行4列的矩阵,一共12个子元素)
int[,] arr = new int[3,4];
二维数组的初始化:
int[,] arr = new int[3,4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
二维数组的遍历:
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i,j] + "\t");
}
Console.WriteLine("");
}
二维数组也可以先定义第一维,然后为每一行定义第二维的长度:
//一个一个元素进行赋值
//string[][] arr = new string[2][];
//arr[0] = new string[2];
//arr[1] = new string[3];
//arr[0][0] = "Good";
//arr[0][1] = "Luck";
//arr[1][0] = "to";
//arr[1][1] = "you";
//arr[1][2] = "!";
//初始化进行赋值
string[][] arr = new string[2][] {
new string[2] { "Good", "Luck" },
new string[3] { "to", "you", "!" }
};
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
Console.Write(arr[i][j] + "\t");
}
Console.WriteLine("");
}
网友评论