1

I would like to compare each element of one array to all elements of another array. What I want to achieve is if an element exists in another array, result =0, otherwise result =1

int m,n;

for(int i=0; i<m; i++) {
  for(int j=0; j<n; j++) {
    if(i==j) {
      result =0;
      //perform a task
       break;
    } 

     if(i!=j) {
       result = 1;
      //perform another task
      break
     }

  }
}

however, i fail to achieve what i want in the second if ()

3
  • 6
    Where is the array? Commented Aug 24, 2012 at 0:05
  • 1
    It's very unclear what you really want to do. Do you want your 'tasks' to run once for each possible combination of elements, or do you won one task or the other to run run only if there is any matching elements or not across the entire arrays? In other words, if you had two arrays that look like {1, 2, 3} and {4, 5, 6}, would you like the 'no match' task to run once or 9 times? Commented Aug 24, 2012 at 1:17
  • I would like 'no match' to run only once. Thanks Commented Aug 24, 2012 at 17:11

1 Answer 1

3

Tweaking your code somewhat (replace char with whatever datatype you're actually using):

char A[50];
char B[50];

for(int i=0; i<50; i++) {     // Iterate through A from 0 to 50
  for(int j=0; j<50; j++) {   // Iterate through B from 0 to 50
    if(A[i] == B[j]) {
       // Item from A exists in B
    }
    else {
       // Item from A does not exist in B
    }
  }
}

Note that the "else" code will run once for every element.

We can do better. First make a utility function that searches an array:

bool item_exists(char item, char[] array, int array_len) {
    for (int i=0; i<array_len; i++) {
       if (array[i] == item)
          return true;
    }
    return false;
}

Then use it.

char A[50];
char B[50];

for(int i=0; i<50; i++) {
    if (item_exists(A[i], B, 50)) {
       // Item from A exists in B
    }
    else {
       // Item from A does not exist in B
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks jonathon. Can you explain to me some more why its better to use char? I intend to use with an array with integer elements, plus i have to deal with many thousand elements.
Then use int. It was just an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.