user2669196
user2669196

Reputation: 175

Printing out a matrix and its transpose, C#

I have a program that creates a transpose 5x8 matrix. I have created an multi dimensional 5x8 array and I also created a new array that hold the transpose of the multi dimensional array. The thing is, I first want to write out the original matrix to the console, and on the same line i want the transpose to be written out. Here is my code:

 class Program
{
    static void Main(string[] args)
    {


        int[,] matrix = new int[5, 8] { 
       { 1, 2, 3, 4, 5,6,7,8 }, 
       { 9,10,11,12,13,14,15,16},
       { 17,18,19,20,21,22,23,24 },
       { 25,26,27,28,29,30,31,32 },
       { 33,34,35,36,37,38,39,40 },

        };

        for (int j = 0; j < 8; j++)
        {
            for (int r = 0; r < 5; r++)
                Console.Write("{0} ", matrix[r, j]);

            Console.WriteLine();
        }

        int[,] newArray = new int[8, 5];
        for (int j = 0; j < 8; j++)
            for (int r = 0; r < 5; r++)
                newArray[j, r] = matrix[r, j];




        Console.ReadLine();

    }
}

what I want is to be shown on the console window is like this: http://pbrd.co/19SXR0J

but I can only print out the transpose matrix. How do I fix this?

Upvotes: 0

Views: 3274

Answers (1)

Gabi Turliu
Gabi Turliu

Reputation: 226

You can just print both lines at a same time, after you computed the transpose.

 for (int j = 0; j < 8; j++)
    {
        //write a line from the first matrix
        for (int r = 0; r < 5; r++)
            Console.Write("{0} ", matrix[r, j]);

        //add some spaces for visual separation
        Console.Write("\t\t");

        //write a line from the transpose matrix
        for (int r = 0; r < 5; r++)
            Console.Write("{0} ", newArray[r, j]);

        Console.WriteLine();
    }

Upvotes: 1

Related Questions