C++ Program to Remove All Occurrences of an Element in an Array

To remove all occurrences of a specific element in an array in C++, you can create a program that iterates through the array and shifts the remaining elements forward whenever the target element is found. This effectively reduces the size of the array and removes all occurrences of the target element.

Here’s an example program that demonstrates how to remove all occurrences of a specified element from an array:

#include <iostream>

int removeElement(int arr[], int size, int element) {

    // Index to store the next element after removing occurrences

    int newSize = 0;

    // Iterate through the array

    for (int i = 0; i < size; i++) {

        // If the current element is not the element to be removed

        if (arr[i] != element) {

            // Move the current element to the position at newSize

            arr[newSize] = arr[i];

            // Increment newSize

            newSize++;

        }

    }

    // Return the new size of the array after removing the element

    return newSize;

}

int main() {

    // Define the array

    int arr[] = {4, 3, 2, 4, 1, 4, 5, 6, 4};

    int size = sizeof(arr) / sizeof(arr[0]);

    // Element to be removed

    int elementToRemove = 4;

    // Remove all occurrences of the element from the array

    int newSize = removeElement(arr, size, elementToRemove);

    // Output the array after removing the element

    std::cout << “Array after removing element ” << elementToRemove << “: “;

    for (int i = 0; i < newSize; i++) {

        std::cout << arr[i] << ” “;

    }

    std::cout << std::endl;

    return 0;

}

Here’s how the Program Works:

  • The function removeElement takes an array, its size, and the element to be removed as parameters.
  • The function initializes a variable newSize to 0, which keeps track of the size of the array after removing occurrences.
  • It iterates through the array, checking each element.
    • If the current element is not the target element (element), it is moved to the position at newSize in the array.
    • The newSize variable is incremented to track the size of the array after removing occurrences.
  • After the loop completes, the function returns the new size of the array.
  • In the main function, the program prints the array after removing the specified element using the returned new size.

Leave a Reply

error: Content is protected !!