OneBite.Dev - Coding blog in a bite size

Add New Item In Array In C++

Code snippet for how to Add New Item In Array In C++ with sample and detail explanation

Adding new items to an array is a common operation in C++ programming. Even though the concept can be a bit tricky for beginners, understanding it can significantly improve your coding skills.

Code Snippet to Add New Item in Array

The following code snippet illustrates how you can add a new item to an array in C++.

#include<iostream>

using namespace std;

int main() {
    //declare an array of five integers
    int arr[5] = {1, 2, 3, 4, 5};

    //display the current array
    cout << "Current array: ";
    for(int i=0; i<5; i++){
        cout << arr[i] << " ";
    }

    //set the 3rd index of the array with a new value
    arr[2] = 10;

    //display the new array
    cout << "\nNew array: ";
    for(int i=0; i<5; i++){
        cout << arr[i] << " ";
    }
    
    return 0;
}

Code Explanation for Adding a New Item in Array

Let’s break down this code into individual parts for better understanding.

  1. First, we include the iostream library which allows for input/output functionalities.

  2. We then declare using namespace std; , which allows us to use objects and variables from the standard C++ library.

  3. In the main function, we declare an integer array arr[] of size 5, and initialize it with five numbers. This is the array that we will be adding a new item to.

  4. Using a for loop, we print out the current contents of the arr array.

  5. To add a “new item” into this array, what we actually do is pick an index of the array and change its value. In this case, we change the 3rd index (which is 2 because C++ array indices start from 0): arr[2] = 10;. Please note that, technically, this does not increase the size of the array, it just changes one of the existing elements.

  6. Finally, we print out the array again with another for loop to show that the item has been added to the array.

c-plus-plus