Insertion of an Elements in an Array C++ Program

In this post, we will see difference operations of insertion of the array in C++.

Inserting Array at the End of an Array.

#include<iostream>
using namespace std;
int main()
{
    //Size of array is 5
    //and we have two more array which is i and elem.
    int arr[5], i, elem;
    //Here we print the Below line in console and take input from arr[i]
    cout<<"Enter 5 Array Elements: ";
    for(i=0; i<4; i++)
        cin>>arr[i];
    //In next line Enter Element to Insert
    cout<<"\nEnter Element to Insert: ";
    cin>>elem;
    //array and elem will be equal
    arr[i] = elem;
    cout<<"\nThe New Array is:\n";
    //here we have increased the size of array.
    for(i=0; i<5; i++)
        cout<<arr[i]<<"  ";
    cout<<endl;
    return 0;
}

//code is contributed by @Tired Programmer

Enter 5 Array Elements: 10
20
30
40

Enter Element to Insert: 50

The New Array is:
10 20 30 40 50

Program finished with exit code 0
Press ENTER to exit the console.

Inserting Array at a specific position.

#include<iostream>
using namespace std;
int main()
{
    int arr[50], i, elem, pos, tot;
    cout<<"Enter the Size for Array: ";
    cin>>tot;
    cout<<"Enter "<<tot<<" Array Elements: ";
    for(i=0; i<tot; i++)
        cin>>arr[i];
    cout<<"\nEnter Element to Insert: ";
    cin>>elem;
    cout<<"At What Position ? ";
    cin>>pos;
    for(i=tot; i>=pos; i--)
        arr[i] = arr[i-1];
    arr[i] = elem;
    tot++;
    cout<<"\nThe New Array is:\n";
    for(i=0; i<tot; i++)
        cout<<arr[i]<<"  ";
    cout<<endl;
    return 0;
}

Enter the Size for Array: 10
Enter 10 Array Elements: 10
20
30
40
50
60
70
90
80
85

Enter Element to Insert: 12
At What Position ? 2

The New Array is:
10 12 20 30 40 50 60 70 90 80 85

…Program finished with exit code 0
Press ENTER to exit console.

Statement, Indentation and Comment in Python
Read My Quora post

Leave a Comment