Delete an element from array ( Using two traversals and one traversal ) | C ++ program to remove a given element from an array ; This function removes an element x from arr [ ] and returns new size after removal ( size is reduced only when x is present in arr [ ] ; Search x in array ; If x found in array ; reduce size of array and move all elements on space ahead ; Driver program to test above function ; Delete x from arr [ ]
#include <bits/stdc++.h> NEW_LINE 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 ; n = deleteElement ( arr , n , x ) ; cout << " Modified ▁ array ▁ is ▁ STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }