C#数组 一维数组、二维数组、三维数组
一位数组:
初始化:int[] arr = new int[5] = {1,2,3,4,5};
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace wm110_5 { class Program { static void Main(string[] args) { int[] arr = new int[5]; //定义一个具有5个元素的数组 Console.WriteLine("请输入一数组:"); for (int i = 0; i < 5; ++i) { arr[i] = Convert.ToInt32(Console.ReadLine()); //往数组中输入值 } for (int i = 0; i < 5; ++i) { int temp = arr[i]; int j = i; while ((j > 0) && (arr[j - 1] > temp)) { arr[j] = arr[j - 1]; --j; } arr[j] = temp; } Console.WriteLine("排序后:"); foreach (int n in arr) { Console.WriteLine("{0}",n); } } } }运行结果:
请输入一数组:
12
12
34
11
53
排序后:
11
12
12
34
53
请按任意键继续. . .
二维数组:
声明一个二维数组: int[,] arr2 = new int[3,2];
初始化:int[,] arr2 = new int[3,2]{{1,2},{3,4},{5,6}};
示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace wm110_6 { class Program { static void Main(string[] args) { Console.Write("请输入数组的行数:"); int row = Convert.ToInt32(Console.ReadLine()); //获取输入的行数 Console.Write("请输入数组的列数:"); int col = Convert.ToInt32(Console.ReadLine()); //获取输入的行数 int[,] arr2 = new int[row, col]; //根据行列实例化一个数组 Console.WriteLine("结果:"); for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { if (i == j) { Console.Write("#"); } else { Console.Write("@"); } } Console.WriteLine(); //换行 } } } }运行结果:
请输入数组的行数:13
请输入数组的列数:14
结果:
#@@@@@@@@@@@@@
@#@@@@@@@@@@@@
@@#@@@@@@@@@@@
@@@#@@@@@@@@@@
@@@@#@@@@@@@@@
@@@@@#@@@@@@@@
@@@@@@#@@@@@@@
@@@@@@@#@@@@@@
@@@@@@@@#@@@@@
@@@@@@@@@#@@@@
@@@@@@@@@@#@@@
@@@@@@@@@@@#@@
@@@@@@@@@@@@#@
请按任意键继续. . .
三维数组:
初始化:int[,,]arr3 = new[2,1,3] = {{{1,2,3}},{{4,5,6}}};
示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace wm110_7 { class Program { static void Main(string[] args) { int[, ,] arr3; //声明一个三维数组 arr3 = new int[,,] { {{ 1, 2, 3 }}, {{ 4, 5, 6 }} }; //初始化三维数组,维数为[2,1,3] foreach (int i in arr3) { Console.WriteLine(i); } } } }运行结果:
1
2
3
4
5
6
请按任意键继续. . .
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。