Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to print the row of a matrix(multi-dimensional array) in a new line

I have a multi-dimensional array in C#, I have assigned the indices of the matrices by capturing input from a user, I am trying to implement a conditional structure that will let me print the rows of my matrix each on a separate line, for example if my array is A and A has a dimension of 3 by 3 then the code prints the first three elements on the first line, the next three elements on the next line and so on and so forth. I am trying to achieve this because it will be easier to understand the structure as a normal matrix and also build an entire matrix class with miscallenous operations.

Code

class Matrix{
 static int[,] matrixA;
 static void Main(string[] args){
   Console.WriteLine("Enter the order of the matrix");
   int n = Int32.Parse(Console.ReadLine());
   matrixA = new int[n, n];
  //assigning the matrix with values from the user
   for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < n; j++)
            {
                matrixA[i, j] = Int32.Parse(Console.ReadLine());
            }
        }
   //the code below tries to implement a line break after each row for the matrix
  for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                
                if( (n-1-i) == 0)
                {
                    Console.Write("\n");
                }
                else
                {
                    Console.Write(matrixA[i, j].ToString() + " ");
                }
            }
        }
    }
}

How do I modify my code so that if the array has 9 elements and its a square matrix then each row with three elements are printed on a single line.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would use something like this for the output:

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            
                Console.Write(matrixA[i, j].ToString() + " ");
        }

        Console.Write("\n");
    }

When the inner loop is done, that means one row has been completely printed. So that’s the only time the newline is needed. (n passes of the outer loop ==> n newlines printed).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading