Display values that are equal by comparing the 2 matrices

Asked

Viewed 102 times

0

For the first time I found myself lost in the exercises I think I didn’t get the logic well, but I’m studying to understand. I will show my source code in full is small and the question. I would like your help to understand where I am missing.

-----Read two 20 x 20 matrices and write the values of the first that occur in any position of the second.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int matrizx[3][3], matrizy[3][3], i, j, cont = 0;
    printf("----Primeira Matriz----\n");
    for (i = 0; i < 3; i++) {
        printf("Informe os X valores da %dº linha \n", (cont = cont + 1));
        for (j = 0; j < 3; j++) {
            scanf("%d", &matrizx[i][j]);

        }
    }

    printf("----Segunda Matriz----\n");
    cont = 0;
    for (i = 0; i < 3; i++) {
        printf("Informe os Y valores da %dº linha \n", (cont = cont + 1));
        for (j = 0; j < 3; j++) {
            scanf("%d", &matrizy[i][j]);

        }
    }
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
                if (matrizx[i][j] == matrizy[i][j]) {
                    printf("%d", matrizx[i][j]);
                }
            }
        }
        return EXIT_SUCCESS;
}

People on this last block that is fallible by doing the analysis that is the question, it can only take the first values repeated, that it find between the matrices only the first line that it finds that the values are equal and displayed such values but it did not proceed with the analysis to display other values. I tried to use an auxiliary variable to help store but to no avail. I’m waiting for some answers, guys!

  • You are checking whether the elements in the same position of the matrices are equal and this is not what the exercise asks. A solution is for each element of the first matrix to compare with all the elements of the second matrix. This variable does not make much sense cont, just print out i+1.

1 answer

0

Follows suggested resolution using python:

def verifica(matriz, numero):
   for linha in matriz:
      for coluna in linha:
         if coluna == numero:
            print(coluna)

for x in matriz1:
   for y in x:
      verifica(matriz2, y)

Note that I made in the second block a loop taking number by number from the first matrix and applying in the function created in the first block. This function, in turn, traverses the second matrix comparing each number of this with the number received in the function parameter. The way you had done, you just compared numbers in equal positions, and the question asks that it just occur in any position of the second. So you sweep the two matrices, comparing the first with everything in the second.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.