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++

Run it Now
#include<iostream>
using namespace std;

int main() {

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

    cout << "Enter Size of an Array :";
    cin>>n;

    cout << "\nEnter Array Elements :";
    for (i = 0; i < n; i++) {
        cin >> arr[i];
    }

    cout << "\nEnter Element for Insert :";
    cin>>num;
    cout << "\nEnter location :";
    cin>>loc;

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

    cout << "\nArray 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 :5
Array List After Insertion :10 20 30 40 44 50