1. 程式人生 > >C#陣列 一維陣列、二維陣列、三維陣列

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
請按任意鍵繼續. . .