数组:相同数据类型的成员组成的一组数据
int[] numbers = {1,3,4,5};
在使用数组之前必须进行初始化赋值
int[ ] numbers;
float[ ] score;
string[ ] names;
初始化数组: 动态初始化 静态初始化
int[] arr = new int[]{1,2,3,4,5,6,8 };
float[] floatarr = {1.0f,2.0f,4.0f,5 };
string[] strArr;
strArr = new string[]{"China","US","Japan" };
动态初始化
数组名 = new 类型 [数组长度]; 类型[] 数组名 = new 类型[数组长度]
numbers = new int[10]; //默认值:0
score = new float[10]; //默认值:0.0f
names = new string[10]; //默认值:null(空对象)
int[ ] number_1 = new int[3]{1,2,3 }; //长度受3限制
int[ ] number_2 = new int[ ]{1,2,3,4 };
string[ ] names_1 = new string[ ]{"China","England","USA" };
静态初始化
int[ ] numbers_3 = {1,2,3,5,6,8};
string[ ] names_2 = { "瓜皮","麻瓜","猪头"}; //0,1,2
通过数组下标访问数组中的成员
string name = names_2[0];
Console.WriteLine(name);
避免下标越界
string[ ] names_2 = { "瓜皮","麻瓜","猪头"}; //0,1,2
string name_1 = names_2[3]; //数组下标越界
数组长度
string[ ] names_2 = { "瓜皮","麻瓜","猪头"};
int a = 2;
if (a < names_2.Length) {
Console.WriteLine (names_2[a]);
}
数组的遍历(循环)
int[ ] numbers_3 = {1,2,3,5,6,8};
numbers_3[5] = 7;
for (int i = 0; i < numbers_3.Length; i++) {
Console.Write (numbers_3[i]);
}
修改数组成员
int[] numbers_3 = {1,2,3,5,6,8};
numbers_3[5] = 7; //8==>7
int[ ] arr = new int[ ]{1,2,3,4,5,6,8 };
float[ ] floatarr = {1.0f,2.0f,4.0f,5 };
int[ ] b = arr;
b [0] = 0;
Console.WriteLine ("{0}",arr[0]); //0
int[ ] intArray = {1,12,34,2,5,6 };
//反向打印数组所有成员
for (int i = intArray.Length-1; i >=0; --i) {
Console.Write (intArray[i]);
}
//求出数组中所有元素的和
int sum = 0;
for (int i = 0; i < intArray.Length; i++) {
sum += intArray [i];
}
Console.WriteLine ("{0}",sum);