How to declare, initialize and print 2D array (matrix) in C#

2 Answers

0 votes
using System;
 
public class Program
{
    public static void Main(string[] args)
    {
       int[,] matrix = new int[3, 4] { { 13, 22, 43, 34 },
                                       { 43, 54, 67, 98 },
                                       { 88, 79, 11, 998 } };
  
        for (int i = 0; i < matrix.GetLength(0); i++) {
            for (int j = 0; j < matrix.GetLength(1); j++) {
                Console.Write("{0, 4}", matrix[i, j]);
            }
            Console.WriteLine();
        }
    }
}
 
 
 
/*
run:
 
  13  22  43  34
  43  54  67  98
  88  79  11 998
 
*/

 



answered Apr 14, 2018 by avibootz
edited Feb 24, 2024 by avibootz
0 votes
using System;
   
public static class Program
{
    public static void Main()
    {
        int[,] arr2d = new int[,] {
            {1, 2, 3, 4},
            {5, 6, 7, 8},  
            {9, 10, 11, 12}  
        };
   
        int rows = arr2d.GetLength(0);
        int cols = arr2d.GetLength(1);
   
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                Console.Write("{0, 3}", arr2d[i, j]);
            }
            Console.WriteLine();
        }
    }
}
   
   
   
   
/*
run:
   
  1  2  3  4
  5  6  7  8
  9 10 11 12
   
*/
 

 



answered Mar 12, 2023 by avibootz
edited Feb 24, 2024 by avibootz

Related questions

...