This blog is under construction

Saturday 27 July 2013

C program to find the union of two arrays

Write a C program to find the union of two arrays.


  #include <stdio.h>
  #define MAX 256
  #define MIN 128

  int main() {
        int arr1[MIN], arr2[MIN], output[MAX];
        int flag, n1, n2, i, j = 0, k;

        /* get the number of entries in first array */
        printf("Enter the number of entries in first array:");
        scanf("%d", &n1);

        /* get the number of entries in second array */
        printf("Enter the number of entries in second array:");
        scanf("%d", &n2);

        /* get the entries of first array from the user */
        printf("Enter your entries for first array:\n");
        for (i = 0; i < n1; i++) {
                printf("Array1[%d]: ", i);
                scanf("%d", &arr1[i]);
        }

        /* get the entries of second array from the user */
        printf("Enter your entries for second array:\n");
        for (i = 0; i < n2; i++) {
                printf("Array2[%d]: ", i);
                scanf("%d", &arr2[i]);
        }

        /* take first element from any given input arrays */
        if (n1 > 0) {
                output[j++] = arr1[0];
        } else if (n2 > 0) {
                output[j++] = arr2[0];
        }

        /* find the union of the given two arrays */
        for (i = 1; i < n1; i++) {
                flag = 0;
                for (k = 0; k < j; k++) {
                        if (arr2[i] == output[k]) {
                                flag = 1;
                                break;
                        }
                }
                /* dont copy the duplicates */
                if (!flag) {
                        output[j++] = arr1[i];
                }
        }

        /* copying unique elements from the second array */
        for (i = 0; i < n2; i++) {
                flag = 0;
                for (k = 0; k < j; k++) {
                        if (arr2[i] == output[k]) {
                                flag = 1;
                                break;
                        }
                }
                /* copy only unique elements */
                if (!flag) {
                        output[j++] = arr2[i];
                }
        }

        /* print the resultant array */
        printf("Resultant Array:");
        for (i = 0; i < j; i++) {
                printf("%d ", output[i]);
        }

        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of entries in first array:5
  Enter the number of entries in second array:5
  Enter your entries for first array:
  Array1[0]: 10
  Array1[1]: 20
  Array1[2]: 30
  Array1[3]: 40
  Array1[4]: 50

  Enter your entries for second array:
  Array2[0]: 40
  Array2[1]: 50
  Array2[2]: 60
  Array2[3]: 70
  Array2[4]: 80
  Resultant Array: 10  20  30  40  50  60  70  80 


1 comment: