How to print 2d-array with a comma and a new line

advertisements
int **arr;  //For example: 4 by 3 array

How can I print 2d-array with comma and new line like below?

01, 02, 03, 04  // At last, new line without comma
05, 06, 07, 08
09, 10, 11, 12

I need the fastest method to print like it.


A simple solution for any m x n matrix defined as a double pointer to type is:

/* print a (m x n) matrix */
void mtrx_prn (size_t m, size_t n, float **matrix)
{
    register size_t i, j;

    for (i = 0; i < m; i++)
    {
        char *pad = "[ ";
        for (j = 0; j < n; j++)
        {
            printf ("%s%6.3f", pad, matrix [i][j]);
            pad = ", ";
        }
        printf ("%s", " ]\n");
    }
}

Output

$ ./bin/mtrx_dyn_example

[  1.900,  2.800,  3.700,  4.600 ]
[  2.800,  3.700,  4.600,  5.500 ]
[  3.700,  4.600,  5.500,  6.400 ]

Just adjust the data type (e.g. int, double, etc...) as needed.