string[] Students = new string[3] { "kaven", "melon", "lucy" };
(4)遍歷數組
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 數組{ class PRogram { static void Main(string[] args) { string[] Students = new string[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 { static void Main(string[] args) { int[,] number = new int[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 { public static int getMultiple(int[] arr) { int result = 1; foreach (int item in arr) { result = result * item; } return result; } static void Main(string[] args) { // 求乘積 int[] number = new int[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 { public static double getSum(params double[] arr) { double sum = 0; for (int i = 0; i < arr.Length; i++) { sum += arr[i]; } return sum; } static void 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 { static void Main(string[] args) int[] a1 = { 1, 2, 3, 4, 5, 6, 7, 8 }; int[] a2=new int[5]; //數組a1從第一個元素開始復制5個元素到數組a2 Array.Copy(a1, a2, 5); Console.WriteLine("數組a2:"); foreach (int i in a2) { Console.Write(i+" "); } Console.WriteLine(); // int[] original = new int[] { 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(); } }}