Group
Arrays and Vectors in C++
Objective
1. Define an array with several integer values.
2. Specify the element to be removed.
3. Loop through the array and search for the element.
4. Once the element is found, shift all the subsequent elements one position to the left to fill the gap.
5. After the shift, decrease the size of the array (or adjust the index accordingly).
6. Test the program by removing different elements from the array.
Develop a program that removes a specific element from an array.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// Function to remove a specific element from the array
void removeElement(int arr[], int& size, int element) {
bool found = false; // Flag to check if the element is found
// Loop through the array to find the element
for (int i = 0; i < size; i++) {
if (arr[i] == element) { // If the element is found
found = true; // Set the flag to true
// Shift all the subsequent elements one position to the left
for (int j = i; j < size - 1; j++) {
arr[j] = arr[j + 1]; // Move each element to the left
}
size--; // Decrease the size of the array
break; // Exit the loop after removing the element
}
}
if (!found) { // If the element was not found
cout << "Element not found in the array." << endl;
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " "; // Print each element of the array
}
cout << endl; // Print a newline at the end
}
int main() {
// Define an array of numbers
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
int elementToRemove = 30; // Element to remove
cout << "Original array: ";
printArray(numbers, size); // Print the original array
// Call the function to remove the element
removeElement(numbers, size, elementToRemove);
cout << "Array after removal: ";
printArray(numbers, size); // Print the array after removal
return 0; // End of program
}
Output
Original array: 10 20 30 40 50
Array after removal: 10 20 40 50