简体   繁体   中英

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM