OneBite.Dev - Coding blog in a bite size

Insert An Element At The End Of An Array In C++

Code snippet for how to Insert An Element At The End Of An Array In C++ with sample and detail explanation

When you start programming in C++, one of the frequent tasks you encounter is managing arrays. This article will demonstrate how to insert an element at the end of an array in C++.

Code snippet for Insertion at End in Array

Here is a simple representation of the process:

#include<iostream>
using namespace std;

int main(){
    int arr[100], size, insert, i;
    cout << "Enter array size : ";
    cin >> size;
    cout << "Enter array elements : ";
    for(i=0; i<size; i++)
    {
        cin >> arr[i];
    }
    cout << "Enter element to be insert : ";
    cin >> insert;
    arr[size] = insert;
    cout << "The array after insertion : ";
    for(i=0; i<=size; i++)
    {
        cout << arr[i]<<" ";
    }
    return 0;
}

Code Explanation for Insertion at End in Array

Let’s breakdown the components of this code and explain what each part does.

  1. Initial Declarations: The initial lines are used to include the necessary library (iostream) and declare that we are going to use the std namespace. The main() function is then defined.

  2. Defining Variables: We define an array arr[100], the size of the array, the element to insert into the array, and a counter i.

  3. Collect User Input: We then prompt the user to enter the array size, the array elements, and finally the element to insert. Our code reads this input using cin.

  4. Insert Element: The element is inserted at the end of the array by assigning it to the index position equivalent to the size of the array (arr[size] = insert;). In an array, the index starts from 0, so if we have size number of elements, the index of the last element is size-1. Thus, arr[size] is actually the next position in the array and suitable for inserting our new element.

  5. Output New Array: The new array’s elements are then output, including the recently inserted element. We use a for loop to go through each element of the array, from 0 to size. Note that this is inclusive of size because we have added a new element to the array.

  6. We then end the main function with a return 0 statement which is a standard way of indicating that the program has successfully run to its completion.

That is all there is to it. Depending on the size of the array and the values input, the output can be observed on the console.

c-plus-plus