C#基础:数组的简单使用

数组是有序的元素序列,下标从0开始,数组必须在访问之前初始化,

示例代码如下:

//一维数组:

  1.             string[] names = { "张三","李四","王五"};
  2.             for (int i = 0; i < names.Length; i++)//for循环输出数组内容
  3.             {
  4.                 Console.WriteLine(names[i]);
  5.             }
  6.             Console.WriteLine();
  7.             foreach (var name in names)//foreach循环输出数组内容,只读,不能修改数组内容
  8.             {
  9.                 Console.WriteLine(name);
  10.             }

  //二维数组,每一组必须有相同元素个数,也可称为矩形数组。

  1.              double[,] aa = { { 1, 2, 3, 4 }, { 2, 3, 4, 5 }, { 3, 4, 5, 6 }, { 5, 6, 7, 8 } };         
  2.             foreach (var a in aa)//foreach循环输出二维数组内容
  3.             {
  4.                 Console.WriteLine("{0}", a);
  5.             }
  6.             Console.WriteLine();
  7.             for (int i = 0; i < aa.GetLength(0); i++)//for循环输出二维数组内容
  8.             {
  9.                 for (int j = 0; j < aa.GetLength(1); j++)
  10.                 {
  11.                     Console.WriteLine("aa[{0},{1}]={2}",i,j,aa[i,j]);
  12.                 }
  13.             }

 //锯齿数组,即数组的数组,每一组元素个数可以不同,元素类型要相同,使用foreach嵌套输出

  1.             int[][] aa = { new int[] { 1 }, new int[] { 1, 2 }, new int[] { 1, 2, 3 } };
  2.             foreach (var a in aa)
  3.             {
  4.                 foreach (var b in a)
  5.                 {
  6.                     Console.WriteLine(b);
  7.                 }
  8.                 Console.WriteLine("---");
  9.             } 

猜你喜欢

转载自blog.csdn.net/QQhelphelp/article/details/83541729