C#将一个二维数组行和列元素互换,即行转列

  //将二维数组行和列互换,存到另一个二维数组中

        public static void CTL(int[,] arr1)
        {
            //执行换行
            int[,] arr2 = new int[3,3];
            for (int i = 0; i < 3; i++)
            {
                for (int j= 0; j < 3; j++)
                {
                    arr2[i, j] = arr1[j,i];
                }
            }
            //将换行数据输出
            Console.WriteLine("互换后:\n");
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(arr2[i, j]+" ");
                }
                Console.WriteLine("\n");
            }
        }

        static void Main(string[] args)
        {
           //程序2二维数组互换位置
            int[,] arr = new int[3, 3] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
            Console.WriteLine("互换前:\n");
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(arr[i, j] + " ");
                }
                Console.WriteLine("\n");
            }
            CTL(arr);

            Console.ReadLine();
        }


posted @ 2022-05-25 15:01  CH|heyi  阅读(645)  评论(0编辑  收藏  举报