This blog is under construction

Wednesday 24 July 2013

C program to compare two arrays

Write a C program to compare two arrays.


  #include <stdio.h>
  #define MAXLIMIT 256

  int main() {
        int data1[MAXLIMIT], data2[MAXLIMIT];
        int i, j, n1, n2, flag = 0;

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

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

        /* Boundary check */
        if (n1 > MAXLIMIT || n2 > MAXLIMIT || n1 < 0 || n2 < 0) {
                printf("Boundary Level Exceeded!!\n");
                return 0;
        }

        /* get the entries for the first array */
        printf("Enter elements for first array:\n");
        for (i = 0; i < n1; i++) {
                printf("Data1[%d]: ", i);
                scanf("%d", &data1[i]);
        }

        /* get the entries for the second array  */
        printf("Enter elements for second array:\n");
        for (i = 0; i < n2; i++) {
                printf("Data2[%d]: ", i);
                scanf("%d", &data2[i]);
        }

        /*
         * if the no of entries in the given arrays are not same, then
         * obviously contents in both the arrays could not be same.
         */
        if (n1 != n2) {
                printf("No of elements in the given arrays not same!!\n");
                return 0;
        }

        /* checking whether the contents in the given arrays are same */
        for (i = 0; i < n1; i++) {
                if (data1[i] != data2[i]) {
                        flag = 1;
                        break;
                }
        }

        /* print the result */
        if (flag) {
                printf("Elements in the given two arrays are not same!!\n");
        } else {
                printf("Elements in the given arrays are same!!\n");
        }

        return 0;
  }



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

  Enter elements for second array:
  Data2[0]: 10
  Data2[1]: 20
  Data2[2]: 30
  Data2[3]: 40
  Data2[4]: 50
  Elements in the given arrays are same!!


No comments:

Post a Comment