How to print the elements of a matrix ordered by rows and by columns in C#

1 Answer

0 votes
using System;

public class PrintMatrixRowsAndColumns_CSharp
{
	public static void printMatrixRows(int[,] matrix) {
		for (int i = 0; i < matrix.GetLength(0); i++) {
			Console.Write("row: {0:D}: ", i);
			for (int j = 0; j < matrix.GetLength(1); j++) {
				Console.Write("{0,4:D} ", matrix[i, j]);
			}
			Console.WriteLine();
		}
	}

	public static void printMatrixColumns(int[,] matrix) {
		for (int j = 0; j < matrix.GetLength(1); j++) {
			Console.Write("column {0:D}: ", j);
			for (int i = 0; i < matrix.GetLength(0); i++) {
				Console.Write("{0,4:D} ", matrix[i, j]);
			}
			Console.WriteLine();
		}
	}

	public static void Main(string[] args)
	{
		 int[,] matrix = {
            {4, 7, 9, 18, 29, 0},
            {1, 9, 18, 99, 4, 3},
            {9, 17, 89, 2, 7, 5},
            {19, 49, 6, 1, 9, 8},
            {29, 4, 7, 9, 18, 6}
        };

		printMatrixRows(matrix);

		Console.WriteLine();

		printMatrixColumns(matrix);
	}
}




/*
run:
  
row: 0:    4    7    9   18   29    0 
row: 1:    1    9   18   99    4    3 
row: 2:    9   17   89    2    7    5 
row: 3:   19   49    6    1    9    8 
row: 4:   29    4    7    9   18    6 

column 0:    4    1    9   19   29 
column 1:    7    9   17   49    4 
column 2:    9   18   89    6    7 
column 3:   18   99    2    1    9 
column 4:   29    4    7    9   18 
column 5:    0    3    5    8    6 
  
*/


 



answered Jul 12, 2024 by avibootz

Related questions

1 answer 192 views
1 answer 135 views
1 answer 151 views
1 answer 193 views
...