Advertisement
alaminrifat

Insertion in Array in C++

Oct 14th, 2020 (edited)
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int main(){
  5.     //n is for total elements in array at this moment
  6.     int arr[10]={2,3,5,6,7},pos,value,i,n=5;
  7.  
  8.     //n++ means n=6 and we put value 8 at sixth position
  9.     arr[n++]=8;
  10.     cout<<"8 added to last position..."<<endl;
  11.  
  12.     //here we shift all the value to next position
  13.     //then at arr[0] mean at 1st position we put value 1
  14.     //after that increase the element value by 1
  15.     for(int i = n ; i > 0 ; i--){
  16.         arr[i] = arr [i-1];
  17.     }
  18.     arr[0]=1;
  19.     n++;
  20.     cout<<"1 added to first position..."<<endl;
  21.  
  22.     //here at position 3 we put value 4
  23.  
  24.     pos = 3;
  25.     value = 4;
  26.  
  27.     // shift all value form last position to the desired position
  28.     for(int i = n ; i >= pos-1 ; i--){
  29.         arr[i] = arr[i-1];
  30.     }
  31.  
  32.     //puting value to the position
  33.     //after that increase the element value by 1
  34.     arr[pos-1] = value;
  35.     n++ ;
  36.     cout<<"4 added to third position..."<<endl;
  37.  
  38.     cout<<"\nThe new array"<<endl;
  39.     //Printing the New Array after adding all new elements
  40.     for (int i = 0; i < n; i++)
  41.     {
  42.         cout<<arr[i]<<" ";
  43.     }
  44.    
  45.  
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement