Delete an element in an Array C++
Q. Write a C++ program to delete an element in an array.
#include <iostream>
using namespace std;
int main()
{
int a[24],i,n,position;
cout << "Enter the number of elements: ";
cin >> n ;
cout << "Enter the integer: ";
for(i=0; i<n; i++)
{
cin >> a[i];
}
cout << "Enter the delete position of an element in an array: ";
cin >> position;
if (position < n+1)
{
for (i = position - 1; i < n - 1; i++)
{
a[i] = a[i+1];
}
cout << "After deleted array of an elements: ";
for (i = 0; i < n - 1; i++)
cout << a[i] << " ";
}
else
{
cout << "Array of element deletion is not possible.";
}
return 0;
}
1. Start
2. Input the number of elements, `n`.
3. Input the `n` integer elements into array `a`.
4. Input the `position` from which the element is to be deleted.
5. Check if the `position` is valid:
- If `position > n` or `position < 1`, print `"Array of element deletion is not possible."` and terminate.
- Else proceed to the next step.
6. Delete the element at the given position:
- For `i` from `position - 1` to `n - 2`:
- Set `a[i] = a[i + 1]`
- (This shifts all elements after the `position` one step left, overwriting the element at `position`.)
7. Reduce the count of elements by 1 (since one element is removed).
8. Print the modified array `a` from index 0 to `n - 2`.
9. End
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com