C++ Program: Insert an Element into an Array
// 2 C++ program - insert an element into an array at a given position.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class Insertion
{
private:
int a[10], n, pos, ele, i; //Data Members
public:
void readdata( );
void insert( ); // Member Function Declaration
void display( );
};
void Insertion::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 of the element in the array"<<endl;
cin>>pos;
cout<<"Enter the element to be inserted"<<endl;
cin>>ele;
}
void Insertion::insert( )
{
if(pos>n)
{
cout<<"Out of array limits!!!";
getch( );
exit(0);
}
else
{
for(i=n; i>=pos; i--)
a[i+1] = a[i]; // Shift array elements
a[pos] = ele; // Insert the given element
n = n+1; // Size of the array is incremented by 1
}
}
void Insertion::display( )
{
cout<<"Array elements after insertion are:"<<endl;
for(i=0; i<n; i++)
cout<<a[i]<<"\t";
}
void main( )
{
Insertion i;
clrscr( );
i.readdata( );
i.insert( );
i.display( );
getch( );
}
Comments
Post a Comment