Predateur 24
Predateur 24

Reputation: 1

Display matrix in C

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

Answers (4)

MikeCAT
MikeCAT

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

y_ug
y_ug

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

P45 Imminent
P45 Imminent

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

CIsForCookies
CIsForCookies

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

Related Questions