C++ Program to insert an element in an array


In this program, You will learn how to insert an element in an array in C++.


List is: 1 2 3 4 5 6

Insert item: 44

Insert location: 7

New list is: 1 2 3 4 5 6 44

Example: How to insert an element in an array in C++.

#include<iostream>
using namespace std;

int main() {

    int arr[10], n, i, num, loc;

    cout << "Enter size of an array:";
    cin>>n;

    cout << "Enter array elements:";
    for (i = 0; i < n; i++) {
        cin >> arr[i];
    }

    cout << "Enter element for insert:";
    cin>>num;
    cout << "Enter location:";
    cin>>loc;

    for (i = n; i >= loc; i--) {
        arr[i] = arr[i - 1];
    }
    n++;
    arr[loc - 1] = num;

    cout << "Array list after insertion:";
    for (i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Output:

Enter size of an array:5
Enter array elements:10 20 30 40 50
Enter element for insert:44
Enter location:3
Array list after insertion:10 20 44 30 40 50