I've been trying to write c programs for finding the union, intersection and difference between two arrays, and while the first two worked out fine, I'm having some trouble finding the difference between two arrays. With difference I mean each element that is in array1, that is not in array2.
I want the third array to contain every element in array1 that is not in array2, and not vica versa. So if array1 is [1, 2, 3], and arr2 is [3, 4, 5], then arr3 is [1, 2]. I am also unsure how to find the difference if the two arrays are of different sizes.
My output is a bunch of zeros and negative numbers:
The difference is: 1
The difference is: 2
The difference is: -14200
The difference is: 0
The difference is: -14340
The difference is: 0
This is the code I've been working with:
#include <stdio.h>
int main()
{
int arr1[100];
int arr2[100];
int size1, size2, i, j, s=0;
//enter array size
printf("\nPlease enter array1 size: \n");
scanf("%d", &size1);
printf("\nPlease enter array2 size: \n");
printf("\n--------------------------- \n");
scanf("%d", &size2);
//setting up a third array to contain the difference
int tot_size = size1+size2;
int arr3[tot_size];
//enter array elements
for(i=0;i<size1;++i)
{
printf("\nPlease enter array1 element %d:\n", i);
scanf("%d", &arr1[i]);
}
printf("\n--------------------------- \n");
for(i=0;i<size2;++i)
{
printf("\nPlease enter array2 element %d:\n", i);
scanf("%d", &arr2[i]);
}
printf("\n--------------------------- \n");
//compare the two arrays, if two elements are not equal
//store them in a third array
for(i = 0; i < size1; i++)
{
for(j = 0; j < size2; j++)
{
if(arr1[i] != arr2[j])
{
arr3[s] = arr1[i];
++i;
++j;
++s;
}
}
}
for(i=0;i<s;++i)
printf("\nThe difference is: %d\n", arr3[i]);
}
Any help would be much appreciated, as I am new to C and still have lots to learn.