Cover Image for Remove an element from an array in C
116 views

Remove an element from an array in C

To remove an element from an array in C, you typically have two approaches:

  1. Create a new array with the element removed.
  2. Modify the original array by shifting elements to cover the removed element.

Here, I’ll demonstrate the second approach, which involves modifying the original array. You can choose to remove an element by its index or its value. Here’s an example of removing an element by its index:

C
#include <stdio.h>

// Function to remove an element by index from an array
void removeElementAtIndex(int arr[], int *size, int index) {
    if (index < 0 || index >= *size) {
        printf("Invalid index. Element not removed.\n");
        return;
    }

    // Shift elements to the left to cover the removed element
    for (int i = index; i < *size - 1; i++) {
        arr[i] = arr[i + 1];
    }

    (*size)--; // Decrement the size of the array
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = 5;
    int index;

    printf("Original Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    printf("\nEnter the index to remove (0 to %d): ", size - 1);
    scanf("%d", &index);

    removeElementAtIndex(arr, &size, index);

    printf("Updated Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

In this program:

  • The removeElementAtIndex function takes the array, its size, and the index of the element to be removed as arguments.
  • It checks if the index is valid, and if so, it shifts all elements to the left, covering the removed element.
  • Finally, it decrements the size of the array to indicate that one element has been removed.

Keep in mind that this approach modifies the original array, so if you need to preserve the original data, you may want to create a copy of the array without the element or use the first approach (creating a new array with the element removed).

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS