How to Remove all the elements from an array having a specific value in C++

In this tutorial, we will learn how to remove all the elements from an array having a specific value.

Removing all the elements from an array having a specific value in C++

In the code, we will make an array having 10 elements and then delete all the elements with the value “2”.

#include <iostream>
using namespace std;

int main()
{
    int array[10]={1,2,2,7,8,2,6,9,0,1};//declaring an array
    int size=10;
    int n = 2;//specific value which we have to remove
    for(int i=0 ; i<size ; i++)
    {
      cout<<array[i];            //printing the original array
    }
    cout<<endl;
    int i=0;
    while(  i <size)             //declaring a loop
    {
        if(array[i]==n)  //checking if element has the value that has to be 
        {                //delted
        if(i<(size-1))  //cheking that our element is not on last position
        {
            for(int j=i ; j<(size-1) ; j++)
            
              array[j]=array[j+1]; //shifting the elements one position 
               size--;              // back to remove specified element      
                 
           
        }
        
        }
        else i++; 
    }
    for(int i=0 ; i<size ; i++){
      cout<<array[i]; //printing updated array
    }
    return 0;
}

Run this code online
Explanation

  1. First, we have declared the array with 10 elements and then store the value that has to be removed in “n”.
  2. Let us assume that we want to delete an element with value 2 from the array having “1,2,3,4,5” elements.
  3. So for this, we can replace the value of “2” with its next element which is “3”.
  4. After that our array will become “1,3,3,4,5” and then we will do the same for all elements after “2”.
  5.  In the end, our array will have “1,3,4,5,5” as elements. Now we will decrease the size of the array by one.
  6. Our final array will have “1,3,4,5” as elements. So we can see that element with value 2 has been removed.
  7. Now we will repeat the above procedure for all positions in the array to remove the particular valued elements.
  8. So in code, we declared the “while” loop inside which we are doing the same procedure as described in the above points.
  9. In the first “if” condition we are simply checking whether the element in the array has the same value which we want to remove.
  10. Then in the next “if” statement we are using for loop to copy the value of elements next to the previous one’s starting from an element that has to be removed.
  11. Finally, we are removing the size of the array and printing the value of an updated array.

Output

1227826901
1786901

Also read: C++ program to calculate simple interest and compound interest

Leave a Reply

Your email address will not be published.