OneBite.Dev - Coding blog in a bite size

remove a specific element from an array in C

Code snippet on how to remove a specific element from an array in C

  int removeElement(int arr[], int n, int elem) 
  { 
      int temp[n], j = 0; 
      for (int i=0; i<n; i++) 
        if (arr[i] != elem) 
            temp[j++] = arr[i]; 
     
      for (int i=0; i<j; i++) 
        arr[i] = temp[i]; 
  
      return j; 
  } 

This code takes an array, the number of elements in the array, and the specific element to be removed. It then creates a temporary array, ‘temp’, and copies over all the elements from the original array that are not equal to the element to be removed. Once the elements are all copied over, the original array is overwritten with the new temporary array, now containing only elements excluding the one to be removed. It then returns the size of the new array.

c