Delete an element from array using two traversals and one traversal in C++?



Two Traversals 

Let us first define the original array and the element to be searched and deleted from the array −

int ele = 5;
int arr = [1,2,3,4];

Now we loop in the array to find the given element −

for (i=0; i

If the given element position is found then we shift the elements to left which are in right to the found element −

if (i < length) {
   length--;
      for (int j=i; j

Example

Let us see the following implementation to see the deletion of element in the array in two traversals −

 Live Demo

#include
using namespace std;

int main() {
   int arr[] = {11, 15, 6, 8, 9, 10};
   int length = sizeof(arr)/sizeof(arr[0]);
   int ele = 6;

 int i;
   for (i=0; i

Output

The above code will produce the following output −

The array after deletion is
11 15 8 9 10

One Traversal

Let us first define the original array and the element to be searched and deleted from the array −

int ele = 15;
int arr = [11,15,6,8,9,10];

Now we declare two variables Boolean found which specifies if the element is found or not and int pos which will store the element position if found −

bool found=false;
int pos=-1;

Next, we search the array and if an element is found we store its position and shift elements while our loop is traversing in a single go.

for (int i=0; i

Example

Let us see the following implementation to see the deletion of element in the array in one traversal only −

 Live Demo

#include
using namespace std;

int main() {
   int arr[] = {11, 15, 6, 8, 9, 10};
   int length = sizeof(arr)/sizeof(arr[0]);
   int ele = 6 ;

bool found=false;
int pos=-1;
   for (int i=0; i

Output

The above code will produce the following output −

The array after deletion is
11 15 8 9 10
Updated on: 2021-01-16T06:48:41+05:30

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements