C++ Program: Delete an Element from an Array
// 3 C++ program - delete an element from an array from a given position.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class Deletion
{
private:
int a[10], n, pos, i;
public:
void readdata( );
void delet( );
void display( );
};
void Deletion::readdata( )
{
cout<<"Enter the size of the array"<<endl;
cin>>n;
cout<<"Enter the elements for the array:"<<endl;
for (i=0; i<n; i++)
cin>>a[i];
cout<<"Enter the position to an delete an element:\n";
cin>>pos;
}
void Deletion::delet( )
{
if(pos>n)
{
cout<<"Out of array limits...!!!";
getch( );
exit(0);
}
else
{
for(i=pos; i<n; i++)
a[i] = a[i+1]; // Move higher position element
n = n-1; // Reduce size of the array by 1
}
}
void Deletion::display( )
{
cout<<"After deletion the array elements are"<<endl;
for(i=0; i<n; i++)
cout<<a[i]<<"\t";
}
void main( )
{
Deletion d;
clrscr();
d.readdata( );
d.delet( );
d.display( );
getche( );
}
Comments
Post a Comment