A macro, max, is defined of size 100. A function, ifexists(), is defined that simply returns true (1) or false (0). The function returns true if the supplied value exists in the specified array, and false if it doesn't.
Two arrays are defined, called p and q, of size max (in other words, 100 elements). You will be prompted to specify the length of the array, p, and then asked to enter the elements in that array. After that, you will be asked to specify the length of array q, followed by entering the elements in array q.
Thereafter, p[0], the first element in array p , is picked up, and by using the for loop, p[0] is compared with all the elements of array q. If p[0] is found in array q, then p[0] is added to the resulting array, r.
After a comparison of p[0], the second element in array p, p[1], is picked up and compared with all the elements of array q. The procedure is repeated until all the elements of array p are compared with all the elements of array q.
If any elements of array p are found in array q, then before adding that element to the resulting array, r, it is run through the ifexists() function to ensure that the element does not already exist in array r. This is because we don't want repetitive elements in array r.
Finally, all the elements in array r, which are the common elements of the two arrays, are displayed on the screen.
Let's use GCC to compile the commoninarray.c program as follows:
D:\CBook>gcc commoninarray.c -o commoninarray
Now, let's run the generated executable file, commoninarray.exe, to see the output of the program:
D:\CBook>./commoninarray
Enter the length of the first array:5
Enter 5 elements in the first array
1
2
3
4
5
Enter the length of the second array:4
Enter 4 elements in the second array
7
8
9
0
There are no common elements in the two arrays
Because there were no common elements between the two arrays entered previously, we can't quite say that we've truly tested the program. Let's run the program again, and this time, we will enter the array elements such that they have something in common.
D:\CBook>./commoninarray
Enter the length of the first array:4
Enter 4 elements in the first array
1
2
3
4
Enter the length of the second array:4
Enter 4 elements in the second array
1
4
1
2
The common elements in the two arrays are:
1
2
4
Voilà! We've successfully identified the common elements between two arrays.