OneBite.Dev - Coding blog in a bite size

find the common elements in two arrays in C

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

  int i, j;
  int arr1[15] = {2, 5, 8, 11, 15};
  int arr2[15] = {1, 4, 5, 6, 9};
  int common[15];

  for(i=0; i<5; i++)
  {
      for(j=0; j<5; j++)
      {
          // check if elements of first
          // array is equal to that of second
          if(arr1[i] == arr2[j])
          {
              // if elements is equal then
              // store it in result array
              common[i] = arr1[i];
          }
      }
  }

This code finds common elements in two arrays, arr1 and arr2. It creates a third array, common, to store the results. It begins by declaring the i and j variables and initializing the two sample arrays.

Then, it goes through a loop to compare the elements of both arrays. If the same element is found in both arrays, it is stored in the common array. The loop finishes after it checks the last element.

Finally, the result array, common, contains all the values both arrays have in common.

c