OneBite.Dev - Coding blog in a bite size

find the unique elements in two arrays in C

Code snippet on how to find the unique elements in two arrays in C

  int i, j;
  int size = 10;
  int arr1[size] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  int arr2[size] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
  
  printf("Unique elements in two arrays\n");
    
  // loop through both arrays
  for (i=0; i<size; i++) {
      // loop through second array
      for (j=0; j<size; j++) {
           // checking if elements of array1 
           // at current index same as
           // element of array2 at current index
           if (arr1[i] == arr2[j])
              break;
      }
    
      // if both the above loops were completed
      // without break statement then it means
      // that there is no repetition
      if (j == size)
          printf("%d ", arr1[i]);
  }

This code will compare two arrays, arr1 and arr2, both of size 10. The for loops go through each array, and if the corresponding elements at each indices are not equal, the element from arr1 is printed as a unique element. This is done by looping through both arrays, and if there is no break the if statement is evaluated and the element is printed. The break statement lets the code know that the element has already been printed, so it will not be considered unique.

c