In this program, I am trying to find values that are common to two arrays and then put those common values into a third array called destination. However, I am putting values from both arrays into destination, when I only want values in source1 to go into destination. How do I fix this?
int common_elements(int length, int source1[length], int source2[length],
int destination[length]) {
int i = 0;
int k = 0;
while (i < length) {
int j = 0;
while (j < length) {
if (source1[i] == source2[j]) {
destination[k] = source1[i];
k++;
}
j++;
}
i++;
}
return k;
}
Assuming that you want the destination array to have all the elements from source1 which are contained in source2 (irrespective of the order of occurrence), all you need to is to add a break; statement after you increment k so that you break out of the inner(j) loop and continue with the next iteration of the outer(i) loop.
If source1 = [1, 2, 3, 4, 5] and source2 = [1, 2, 3, 2, 1]
Your code will result in destination = [1, 1, 2, 2, 3]
If you add a break statement as suggested above, the code will result in destination = [1, 2, 3, (garbage value), (garbage value)].
To get rid of garbage values you can initialize the destination array with 0s or -1s before passing it to the method.
If you are interested in only the number of common elements, a break statement should be enough.
Edit:
Added the code:
int common_elements(int length, int source1[length], int source2[length],
int destination[length]) {
int i = 0;
int k = 0;
while (i < length) {
int j = 0;
while (j < length) {
if (source1[i] == source2[j]) {
destination[k] = source1[i];
k++;
break;
}
j++;
}
i++;
}
return k;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With