1
votes

I'm learning C, and trying to print a boolean matrix (5 x 5) from couples of numbers (edges of a graph) in input. If the position of the elements in the matrix has corresponding edges it is "1", otherwise "0". For example:

I put as input: 1 2, 1 4, 2 4, 2 3, 3 5

I want that in the position (1,2) and (2,1); (1,4) and (4,1); (2,4) and (4,2); (2,3) and (3,2), (3,5) and (5,3) it prints 1, but 0 in all the others.

This is what I was able to write, but doesn't really work:

(I have studied multidimensional arrays, but I can't see if they might be useful for this case.)

int i, j;

int array1[5], array2[5];

for (i = 0; i < 5; ++i)
    {
    printf("Insert the edges %d of the graph\n", i);
    scanf("%d %d", &array1[i], &array2[i]);
    } 

printf("{");
for (i = 0; i < 5; ++i)
printf("(%d,%d)", array1[i], array2[i]);
printf("}\n");

for (i = 0; i < 5; ++i) {
    for (j = 0; j < 5; ++j) 
        if (((array1[i] == i+1) && (array2[i] == j+1)) || ((array1[i] == j+1) && (array2[i] == i+1))) printf("%d ", 1); 
        else printf("%d ", 0); 
        printf("\n");  }

What I should see (with those sample inputs):

http://imageshack.com/a/img537/9986/jx5roa.png

What I get:

http://imageshack.com/a/img537/6341/kroVQK.png

Thank you for your time!

1
Can you post some sample output from what you've tried so far? That is, can you clarify in what ways it's not working?Matt

1 Answers

3
votes

You should create the 2-dimensional array. Initially fill it with all zeroes, then when the user enters the edges you change those elements to one.

#define SIZE 5
int array[SIZE][SIZE];
int i, j;
// Initialize array to 0
for (i = 0; i < SIZE; i++) {
    for (j = 0; j < SIZE; j++) {
        array[i][j] = 0;
    }
}

// Get edges from user
for (i = 0; i < SIZE; i++) {
    int e1, e2;
    printf("Insert the edges %d of the graph\n", i);
    scanf("%d %d", &e1, &e2);
    // Set them to 1
    array[e1-1][e2-1] = 1;
    array[e2-1][e1-1] = 1;
}

// Display the array
for (i = 0; i < SIZE; i++) {
    for (j = 0; j < SIZE; j++) {
        printf("%d ", array[i][j]);
    }
    printf("\n");
}