Write a program to insert an element into an array at a given position

#include<iostream.h> #include<iomanip.h> class insertion { private: int n, m[100], ele, p; public: void getdata(); void insert(); void display(); }; void insertion::getdata() { cout<<"How many elements?"; cin>>n; cout<<"Enter the elements: "; for(int i=0; i<n; i++) cin>>m[i]; cout<<"Enter the element to be inserted:"; cin>>ele; cout<<"Enter the position (0 to "<<n<<"):"; cin>>p; } void insertion::insert() { if(p>n) { cout<<p<<"is an invalid position"; exit(0); } else { for(int i=n-1; i>=p; i--) m[i+1] = m[i]; m[p] = ele; n = n+1; cout<<ele<<" is successfully inserted"<<endl; } } void insertion::display() { cout<<"The array after the insertion is "; for(int i=0; i<n; i++) cout<<setw(4)<<m[i]; } void main() { insertion I; I.getdata(); I.insert(); I.display(); }
[wp_ad_camp_1]
OUTPUT ------ How many elements? 5 Enter the elements: 20 30 40 50 60 Enter the elements to be inserted: 10 Enter the position ( 0 to 5): 0 10 is successfully inserted into position 0 The array after the insertion is 10 20 30 40 50 60 --- How many elements? 5 Enter the elements: 10 20 30 50 60 Enter the elements to be inserted: 40 Enter the position ( 0 to 5): 3 10 is successfully inserted into position 3 The array after the insertion is 10 20 30 40 50 60 -- How many elements? 5 Enter the elements: 10 20 30 40 50 Enter the elements to be inserted: 60 Enter the position ( 0 to 5): 5 10 is successfully inserted into position 5 The array after the insertion is 10 20 30 40 50 60 --- How many elements? 5 Enter the elements: 10 20 30 40 50 Enter the elements to be inserted: 60 Enter the position ( 0 to 5): 7 7 is an invalid position