Reputation: 5438
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.
Upvotes: 0
Views: 1810
Reputation: 40145
int row = 3, col=4;
char outbuff[(11+2)*row*col];
register char *p=outbuff;
for(int r = 0; r < row; ++r){
for(int c = 0; c < col; ++c){
if(c){
*p++ = ',';
*p++ = ' ';
}
p += sprintf(p, "%02d", arr[r][c]);
}
*p++ = '\n';
}
*p = 0;
fputs(outbuff, stdout);
Upvotes: 0
Reputation: 84579
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.
Upvotes: 2
Reputation: 4738
You can use below logic to achieve that. Use conditional printf
to skip comma for last term. And next time post what you have tried :)
for(int row=0;row<MaxRow;row++)
{
for(int col=0;col<MaxCol;col++)
{
if(col == MaxcCol-1)
printf(" %d",array[row][col]);
else
printf(" %d,",array[row][col]);//comma after %d
}
printf("\n");
}
Upvotes: 0