数组的学习:(下面是学习的内容和一些例子)
数组 :相同数据类型的成员组成的一组数据
int[] numbers = {1,3,4,5};
1.在使用数组之前必须进行初始化赋值
2.初始化数组:动态初始化,静态初始化
int [] numbers;
float[] score;
string[] names;
动态初始化:
类型[] 数组名 = new 类型 [数组长度];
numbers = new int[10] ;//默认值:0
score = new float[10];//默认值:0.0f
names = new string[10];//默认值:null (空对象)
int numer_1 = new int[3] { 1, 2, 3, };
int numer_2 = new int[4] { 1, 2, 3, 4 };
string names_1 = new string[] { "China", "English", "Usa" };
静态初始化
int [] numbers_3 = {1,2,3,4,5};
string[] names_2 = { "显冲", "牛逼", "狗子" };//0 1 2
3.通过数组下标访问数组中的成员
string name = names_2[0];
Console.WriteLine(name);
避免下标越界
string name_1= names_2[3];
数组长度
int a = 3;
if (a < names_2.Length) {
Console.WriteLine (names_2 [a]);
}
4.数组的遍历
numbers_3[5] =7 ;//修改数组的成员
for (int i = 0; i < numbers_3.Length; ++i) {
Console.WriteLine (numbers_3 [i]);
}
int[] intArray = {1,12,34,2,5,6} ;
5.反向打印数组所有成员
for (int i = intArray.Length - 1; i >= 0; --i) {
Console.WriteLine ("{0}", intArray [i]);
}
6.练习习题:
求数组中所有元素之和
int sum =0;
for (int i = 0; i < intArray.Length; ++i) {
sum += intArray [i];
}
Console.WriteLine ("{0}", sum);