DEV Community

Cover image for How to insert an element in an array in C++
Mujahida Joynab
Mujahida Joynab

Posted on

How to insert an element in an array in C++

Code to insert an element in an array -

#include <bits/stdc++.h>
using namespace std;
int a[100000];
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    int value, index;
    cin >> value >> index;

    n++;
    for (int i = n - 1; i >= index; i--)
    {
        a[i + 1] = a[i];
    }
    a[index] = value;

    for (int i = 0; i < n; i++)
    {

        cout << a[i] << " ";
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)