2009年12月6日日曜日

System.Arrayクラスの静的メソッドSort、Reverse、Clearを使用し配列を操作してみる。

using System;

class MainClass
{
    static void DisplayArray(int[] a)
    {
        foreach (int n in a)
        {
            Console.Write("{0} ", n);
        }
        Console.WriteLine("");
    }
    static void Main()
    {
        int[] array = { 1, 3, 5, 7, -1, -3, -5, -7 };

        // 配列を表示する
        DisplayArray(array);

        // 配列を昇順に並び替える
        Array.Sort(array);
        DisplayArray(array);

        // 配列を反転させる(昇順から降順になる)
        Array.Reverse(array);
        DisplayArray(array);

        /* 配列の要素を既定値に初期化
         * (index 2(数値3)から4つの要素を0にする。)
         * 出力値:7 5 0 0 0 0 -5 -7 */
        Array.Clear(array, 2, 4);
        DisplayArray(array);
    }
}

0 コメント:

コメントを投稿