Remove a Specific Element from an Array in C++
In this exercise, you will develop a program that removes a specific element from an array. Removing elements from an array is a common task, especially when working with data that may need modification or updating.
The goal is to identify a specific element within the array, remove it, and shift the remaining elements to fill the gap. This exercise will help you practice working with arrays, loops, and element manipulation in C++.
Logic Components
1. Search
We first locate the index of the target element. If the element doesn't exist, no further action is taken.
2. Shifting
To "remove" the element, we shift all elements to its right one position to the left (arr[j] = arr[j+1]).
3. Resize
Since static arrays cannot truly shrink, we decrement the size variable to ignore the last (now duplicate) element.
Pro Tip:
In real-world C++ development, using std::vector with erase() is more efficient and safer than manually shifting elements in a static array.
Learning Objectives
- 1. Identify the target value within an array using a loop.
- 2. Implement a nested loop or shift logic to overwrite the target.
- 3. Understand Pass-by-Reference (
int& size) to modify the size variable outside the function. - 4. Validate data state before and after the removal process.
Solution Implementation
#include <iostream>
using namespace std;
// Function to remove a specific element from the array
void removeElement(int arr[], int& size, int element) {
bool found = false;
// Loop through the array to find the element
for (int i = 0; i < size; i++) {
if (arr[i] == element) {
found = true;
// Shift all subsequent elements one position to the left
for (int j = i; j < size - 1; j++) {
arr[j] = arr[j + 1];
}
size--; // Decrease the logical size
break; // Exit after the first match is removed
}
}
if (!found) {
cout << "Element not found in the array." << endl;
}
}
// Function to print the current state of the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
int elementToRemove = 30;
cout << "Original array: ";
printArray(numbers, size);
removeElement(numbers, size, elementToRemove);
cout << "Array after removal: ";
printArray(numbers, size);
return 0;
}
Console Output:
Array after removal: 10 20 40 50