LAST UPDATED: OCTOBER 31, 2020
C++ How to Delete an Array element
Hello Everyone!
In this tutorial, we will learn how to perform the deletion of an array element at a particular position, in the C++ programming language.
Let's first understand what does deletion of an element refers to in an Array.
Deletion refers to removal of an element from an Array, without effecting the sequence of the other elements. Here the key task is to make sure that once the element gets deleted, the other elements are to be moved accordingly so that they are still stored in the continuous form thereby following the property of an Array.
Logic:
Once the element gets removed, move all the elements following it, towards the front by 1 position. This way, the remaining elements will still be stored in a continuous form. The below code will help you understand this logic.
Code:
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to demonstrate Deletion of an element from an Array ===== \n\n";
int n;
cout << " Enter the size of the array: ";
cin >> n;
int arr[n], i, pos;
cout << "\n\n Enter the " << n << " elements of the array: \n\n";
for(i=0; i<n; i++)
{
cin >> arr[i];
}
//Printing the original array before deletion
cout << "\n\n The " << n << " elements of the array, before deletion are : \n\n";
for(i=0; i<n; i++)
{
cout << arr[i] << " ";
}
cout << "\n\n Enter the position, between 1 and " << n << " , of the element to be deleted : ";
cin >> pos;
//Performing the deletion logic
--pos;//as index of the element to be deleted is 1 less than it's position
for (i = pos; i <= 9; i++)
{
arr[i] = arr[i + 1];
}
cout << " \n\nThe " << n-1 << " elements of the array, after deletion are : \n\n";
for(i=0; i<n-1; i++)
{
cout << arr[i] << " ";
}
cout << "\n\n";
return 0;
}
Output:
We hope that this post helped you develop a better understanding of the concept of the Deletion of an Array element in CPP. For any query, feel free to reach out to us via the comments section down below.
Keep Learning : )