Programming Problem C - Vectors

Asked

Viewed 83 times

0

The problem is:

Write an algorithm that reads 3 vectors A[1..10], B[1.10] e C[1..10] and write the elements that are in A and B (intersection) but are not in C. Write the values in the order they appear in vector A. The three vectors should be read separately (first, all the vector A, after vector B and finally vector C).

My solution (which is not running):

#include <stdio.h>
int main() 
{
  int A[10], B[10], C[10], i, j, k;
  for (i=0; i<=9; i++) 
    scanf ("%d",&A[i]);
  for (j=0; j<=9; j++) 
    scanf ("%d",&B[j]);
  for (k=0; k<=9; k++) 
  scanf ("%d",&C[k]);

  for (i=0; i<=9; i++) 
    {
      for (j=0; j<=9; j++) 
        {
          if (A[i]==B[j]) 
            {
              for (k=0; k<=9; k++) 
                {
                  if (A[i]!=C[k]) 
                    printf ("%d\n",C[k]);
                }
            }    
        }
    }
}

Where is the error and how can I correct it?

1 answer

1

You are reading the 3 vectors correctly, and comparing the vectors A and B correctly and in the order of A. The problem is the third loop, when you search for the content of C.

Here, you are printing all in C that are different from the element in A being compared, in fact you need to check if any in C is equal to the element of A being checked, and if you have no print.

The loop I think can stay like this:

// dentro do if (A[i] == B[j]) {
int repetidos = 0;
for(int k = 0; k <= 9; k++) {
  // se repetir, incrementa
  if (A[i] == C[k]) {
    repetidos++;
  }
}
// sem repetidos? então imprime
if (repetidos == 0) {
  printf("%d\n", A[i]);
}
  • It hasn’t worked yet, but it has helped! Thank you!

  • 1

    had to take the if inside the loop... I edited the answer

Browser other questions tagged

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