How to Remove an Element from Array in C++?
Last Updated :
05 Mar, 2024
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++
#include <array>
#include <iostream>
using namespace std;
int deleteElement( int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
break ;
if (i < n) {
n = n - 1;
for ( int j = i; j < n; j++)
arr[j] = arr[j + 1];
}
return n;
}
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] << " " ;
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)
Share your thoughts in the comments
Please Login to comment...