OneBite.Dev - Coding blog in a bite size

Insert An Element At A Specific Index In An Array In C++

Code snippet for how to Insert An Element At A Specific Index In An Array In C++ with sample and detail explanation

Manipulating arrays forms the backbone of a variety of data handling tasks in programming. In C++, adding an element at a specific index requires understanding the fundamentals of array data structure. This article provides a straightforward example of how to achieve this goal.

Code Snippet: Inserting an Element at a Specific Index

#include<iostream>
using namespace std;

// Function to insert x in arr at position index
void insertAtIndex(int arr[], int index, int x, int n)
{
    // shift elements of arr[0..index-1], to one position to their right
    for (int i=n-1; i>=index; i--) {
        arr[i+1] = arr[i];
    }

    // insert x at position index
    arr[index] = x;
}

int main()
{
    int arr[20] = {5, 10, 30, 20, 40};
    int x = 50;
    int n=5;
    int index = 3;
    insertAtIndex(arr, index, x, n);
    n++;

    cout << "Updated array is: ";
    for (int i=0; i<n; i++)
        cout << arr[i] << " ";
  
    return 0;
}

Code Explanation for Inserting an Element at a Specific Index

In this code, we define the function insertAtIndex, which takes an array, an index at which an element needs to be added, the element to be added (x), and the actual number of elements in the array (n) as parameters.

Here are the steps involved:

  1. We begin by iterating over our array from the last element (at position n-1) to our desired index in a reverse manner. For each of these elements, we shift them by one position to the right. This makes space at our desired index.

  2. Once we’ve created space at our desired index, we insert our element x at this position.

  3. In the main function, we call insertAtIndex with parameters being our array, index where we want to insert an element, the element (50) to be inserted, and the number of present elements in array (n).

  4. After insertion, we increment the size of our array n by 1 as the total number of elements has increased.

  5. Finally, our updated array is printed out to confirm that the element x has been successfully added at the desired index.

By following this method, you can easily insert an element at any specific index in an array in C++.

c-plus-plus