Home > Back-end >  Print multidimensional array value with comma separated in C#
Print multidimensional array value with comma separated in C#

Time:03-01

How to print multidimensional array value with comma separated in C#

How to add curly braces each row during printing the array like array initialization declaration

CodePudding user response:

             int[,] array_1 = new int[3, 6]
            {
                {12,12,23,34,34,4 },
                {32,43,12,45,34,4 },
                {54,21,12,43 ,34,4}
            };
             
            for (int i = 0; i < array_1.GetLength(0); i  )
            {
                int j = 0;
                for (j = 0; j < array_1.GetLength(1); j  )
                {
                    if (j == 0)
                    {
                        Console.Write("{");
                    }
                    Console.Write(array_1[i, j]);
                    if (array_1.GetLength(1) > j   1)
                    {
                        Console.Write(", ");
                    }
                }

                Console.Write("}");
                Console.WriteLine();
            }
            Console.ReadLine();

CodePudding user response:

You can print the 2D array like this:

for (int i = 0; i < array_1.GetLength(0); i  )
{
    // unconditionally start every line with a {
    Console.Write("{");    
    // print comma separated except the last element
    for (int j = 0; j < array_1.GetLength(1)-1; j  )
    {
        Console.Write(array_1[i, j]);
        Console.Write(", ");
    }
    // last element
    Console.Write(array_1[i, array_1.GetLength(1)-1]);
    // unconditionally end every line with a }
    Console.WriteLine("}");  
}
  • Related