How it works...

We defined two arrays called p and q. We don't want to fix the length of these arrays, so we should define a macro called max of value 100 and set the two arrays, p and q, to the size of max.

Thereafter, you will be prompted to specify the size of the first array and enter the elements in the first array, p. Similarly, you will be asked to specify the length of the second array, q, followed by entering the elements in the second array.

Let's assume you have specified the length of both arrays as 4 and have entered the following elements:

Figure 1.14

We need to pick up one element at a time from the first array and compare it with all the elements of the second array. If an element in array p does not appear in array q, it will be assigned to the third array we created, array r.

Array r will be used for storing the elements that define the difference between two arrays. As shown in Figure 1.15, the first element of array p, in other words, at p[0], is compared with all the elements of array q, in other words, with q[0], q[1], q[2], and q[3].

Because the element at p[0], which is 1, does not appear in array q, it will be added to the array r, indicating the first element representing the difference between the two arrays:

Figure 1.15

Because the element at p[1], which is 2, appears in array q, it is discarded, and the next element in array p, in other wordsp[2], is picked up and compared with all the elements in array q.

As the element at p[2] does not appear in array q, it is added to array r at the next available location, which is r[1] (see Figure 1.16 as follows):

Figure 1.16

Continue the procedure until all the elements of array p are compared with all the elements of array q. Finally, we will have array r, with the elements showing the difference between our two arrays, p and q.

Let's use GCC to compile our program, differencearray.c, as follows:

D:CBook>gcc differencearray.c -o differencearray

Now, let's run the generated executable file, differencearray, to see the output of the program:

D:CBook>./differencearray
Enter length of first array:4
Enter 4 elements of first array
1
2
3
4
Enter length of second array:4
Enter 4 elements of second array
2
4
5
6
The difference of the two array is:
1
3

VoilĂ ! We've successfully found the difference between two arrays. Now, let's move on to the next recipe!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset