In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we are going to discuss how to remove a value from an array in C++.
Example:
Input: arr[] = {3, 1, 2, 5, 90}, x = 2 Output: arr[] = {3, 1, 5, 90}
Remove an Element from an Array in C++
To remove a value from an array in C++, we first search ‘x’ in the array, then move elements that are on the right side of x to one position towards the front (i.e. towards the left).
Approach
- Search for the element in the array by iterating over the array using a for loop.
- Check if the element is found in the array.
- If the element is found, reduce the size of the array and move all elements one space ahead.
- Return the new size of the array.
C++ Program to Remove an Element from Array
C++
// C++ program to illustrate how to remove a given element // from an array #include <array> #include <iostream> using namespace std;
// This function removes an element x from arr[] and // returns new size after removal (size is reduced only // when x is present in arr[] int deleteElement( int arr[], int n, int x)
{ // Search x in array
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
break ;
// If x found in array
if (i < n) {
// reduce size of array and move all
// elements on space ahead
n = n - 1;
for ( int j = i; j < n; j++)
arr[j] = arr[j + 1];
}
return n;
} // Driver code int main()
{ int arr[] = { 11, 15, 6, 8, 9, 10 };
int n = sizeof (arr) / sizeof (arr[0]);
int x = 6;
cout << "Before Modification array is \n" ;
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
// Delete x from arr[]
n = deleteElement(arr, n, x);
cout << "\n After Removal of " << x << " from array\n" ;
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
return 0;
} |
Output
Before Modification array is 11 15 6 8 9 10 After Removal of 6 from array 11 15 8 9 10
Time Complexity: O(N)
Auxiliary Space: O(1)