Reputation: 1
I had searched so much on the forum, but I didn't find a solution for my problem.
How do I print a matrix that is given like this matrix[2][2]={{1,2},{3,4}}
and give it back like:
1 2
3 4
Upvotes: 1
Views: 215
Reputation: 75062
This program support not only 2x2 matrix but also int matrix[2][3]={{1,2,3},{4,5,6}};
or other size.
#include <stdio.h>
int main(void) {
int matrix[2][2]={{1,2},{3,4}};
size_t i, j;
for (i = 0; i < sizeof(matrix)/sizeof(matrix[0]); i++) {
for (j = 0; j < sizeof(matrix[i])/sizeof(matrix[i][0]); j++) {
if (j > 0) putchar(' ');
printf("%d", matrix[i][j]);
}
putchar('\n');
}
return 0;
}
Upvotes: 2
Reputation: 1124
#include <stdio.h>
int main(){
int i,j;
int x [2][2]={{1,2},{3,4}};
for(i=0; i<2; i++) {
for(j=0; j<2; j++) {
printf(" %d", x[i][j]);
}
printf("\n");
}
}
Upvotes: 3
Reputation: 8591
for (int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
printf("%d\t", matrix[i][j]); // tab-separated. Did you want a space?
}
if (i < 2 - 1) printf("\n"); // newline except at the end
}
is one way.
Upvotes: 1
Reputation: 12817
Simple nested for loop:
for (int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
Upvotes: 1