string[] Students = newstring[3] { "kaven", "melon", "lucy" };
(4)遍历数组
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数组
{
class Program
{
staticvoid Main(string[] args)
{
string[] Students = newstring[3] { "kaven", "melon", "lucy" };
//for (int i = 0; i < Students.Length; i++)//{// Console.WriteLine(Students[i]);//}
Console.WriteLine("学生列表:");
Console.WriteLine("++++++++++++++++++++++++++");
foreach (string s in Students) {
Console.WriteLine(s);
}
Console.WriteLine("++++++++++++++++++++++++++");
//通过索引访问数组元素
Console.WriteLine("第三个学生是:" + Students[2]);
Console.ReadKey();
}
}
}
3.二维数组
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数组
{
class Program
{
staticvoid Main(string[] args)
{
int[,] number = newint[5, 2]{
{0,0},
{1,1},
{2,4},
{3,9},
{4,16}
};
Console.WriteLine("++++++++++++++++++");
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 2; j++) {
Console.WriteLine("第{0}行{1}列为{2}",i,j,number[i,j]);
}
}
Console.WriteLine("++++++++++++++++++");
Console.ReadKey();
}
}
}
4.数组参数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数组
{
class Program
{
publicstaticintgetMultiple(int[] arr)
{
int result = 1;
foreach (int item in arr)
{
result = result * item;
}
return result;
}
staticvoid Main(string[] args)
{
// 求乘积int[] number = newint[5] { 1, 3, 5, 7, 9 };
Console.Write("数组元素");
foreach (int i in number) {
Console.Write(i+"、");
}
Console.Write("的乘积是");
Console.Write(getMultiple(number));
Console.ReadKey();
}
}
}
5.参数数组
参数数组通常用于传递未知数量的参数给函数。
格式
public 返回类型 方法名称( params 类型名称[] 数组名称 )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数组
{
class Program
{
publicstaticdoublegetSum(paramsdouble[] arr) {
double sum = 0;
for (int i = 0; i < arr.Length; i++) {
sum += arr[i];
}
return sum;
}
staticvoid Main(string[] args)
{
Console.WriteLine(getSum(1.2, 2.3, 3.4, 4.5));
Console.ReadKey();
}
}
}
结果
把 params关键字去掉就会报错
6.Array
Array 类提供了各种用于数组的属性和方法,是所有数组的基类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数组
{
class Program
{
staticvoid Main(string[] args)
int[] a1 = { 1, 2, 3, 4, 5, 6, 7, 8 };
int[] a2=newint[5];
//数组a1从第一个元素开始复制5个元素到数组a2
Array.Copy(a1, a2, 5);
Console.WriteLine("数组a2:");
foreach (int i in a2) {
Console.Write(i+" ");
}
Console.WriteLine();
//int[] original = newint[] { 78, 12, 39, 90, 64, 56, 30, 2, 7 };
int[] temp = original;
//原始数组
Console.WriteLine("原始数组");
foreach (int i in original)
{
Console.Write(i + " ");
}
Console.WriteLine();
//逆转数组
Array.Reverse(temp);
Console.WriteLine("逆转数组");
foreach (int i in temp)
{
Console.Write(i + " ");
}
Console.WriteLine();
//排序数组
Array.Sort(temp);
Console.WriteLine("排序数组");
foreach (int i in temp)
{
Console.Write(i + " ");
}
Console.ReadKey();
}
}
}