remove a element from an array c++

To remove an element from an array in C++, you can follow these steps:

  1. Determine the index of the element you want to remove from the array.

  2. Shift all the elements after the desired index to the left, effectively overwriting the element you want to remove.

  3. Update the size of the array to reflect the removal of the element.

Here's an example code snippet that illustrates the process:

#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    int index = 2;

    // Print the original array
    std::cout << "Original Array: ";
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    // Remove the element at the given index
    for (int i = index; i < size - 1; i++) {
        arr[i] = arr[i + 1];
    }
    size--;

    // Print the modified array
    std::cout << "Modified Array: ";
    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

In this example, we have an array arr with elements {1, 2, 3, 4, 5}. We want to remove the element at index 2 (which is the number 3). The code shifts all the elements after index 2 to the left, overwriting the element at index 2. The size of the array is then updated to reflect the removal of the element. Finally, the modified array is printed to verify the removal.

I hope this helps! Let me know if you have any further questions.