Equal elements between vectors - C

1

I'm trying to solve a problem early on which is as follows:

  

A school wants to know if there are   disciplines Logic and e Programming language. Enter the numbers   of the students that study the Logic in a vector at most   of 5 students. Enter the enrollment numbers of the students taking the course   Language in another vector, up to 5 students. Display the   which appears in both vectors.

It's still running, but when I put numbers out of order it's bugging. If you can help me, thank you, because I am breaking my head on this issue and it is catching me to finish the rest of the others, seems to be lazy to think, but I have been locked in this question since early.

From-already thank you

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

int i, a;
int mat1[6], mat2[6];

int main(void){

    setlocale(LC_ALL, "Portuguese");

    for(i=0 ; i<5; i++){

        printf("DIGITE AS MATRÍCULAS DOS ALUNOS DE LÓGICA DE PROGRAMAÇÃO: ");
        scanf("%d", &mat1[i]);
    }

    printf("\n");

    for(i=0; i<5; i++){

        printf("DIGITE AS MATRÍCULAS DOS ALUNOS DE LINGUAGEM DE PROGRAMAÇÃO: ");
        scanf("%d", &mat2[i]);
    }

    printf("\n");

    for(i=0; i<5; i++){

        for(a=5; a>=0; a--)
        {
            if(mat1[i] == mat2[a] || mat1[a] == mat2[i]) printf("AS MATRÍCULAS IGUAIS SÃO: %d\n", mat1[i]);
        }
    }

return 0;
}

Running the program:

    
asked by anonymous 29.10.2018 / 21:28

1 answer

1

You have several small bugs in your code that make it impossible for you to get the result you expect. Notice that in the second% w / o of% that the repeated enrollment finds the number of elements is not the same:

for(i=0; i<5; i++){    
//    ^----^ de 0 a 4 são 5 elementos
    for(a=5; a>=0; a--)
    //    ^-----^--- de 5 a 0 são 6 elementos

Here you can see that a for traverses 5 elements and another for . In addition, when accessing 6 elements you are accessing more elements than you filled in, and you are not only doing invalid access in memory because you declared the vectors with 6 houses when you only needed 5. This is also something that you should avoid doing .

You also do not have to walk around in an ever increasing fashion with 6 and another decreasing with i++ . It is simpler to do both normally from a-- to 0 .

The condition that has 4 is also not what you need because you just need to validate if the element given by the first if(mat1[i] == mat2[a] || mat1[a] == mat2[i]) in the for vector is equal to what is in the mat1 vector with the variable of the second mat2 , that is, for .

Correcting the block of if(mat1[i] == mat2[a]) end already gives the result you expect:

for(i=0; i<5; i++){
    for(a=0; a<5; a++){
        if(mat1[i] == mat2[a]) printf("AS MATRÍCULAS IGUAIS SÃO: %d\n", mat1[i]);
    }
}

See it working on Ideone

    
30.10.2018 / 01:44