How to Add an Element at the Beginning of an Array in C++?
In C++, arrays are static data structures with a fixed size, hence directly adding new elements at the front or middle is not supported in C++ like any other dynamic data structure. In this article, we will learn how we can add an element at the beginning of an array in C++.
Example:
Input:
original_array = {10, 20, 30, 40, 50}
element_to_add = 5
Output:
updated_array: 5 10 20 30 40 50
Adding an Element at the Beginning of an Array in C++
If we have a large enough array with some unused space at the end we can simply add an element at the beginning of an array by shifting all elements one position to the right and then adding the new element at the first position.
Approach
- First, create a large enough array that has space to insert an extra element.
- Now, loop from the last element to avoid overwriting the next element and shift all current elements one position to the right by setting
arr[i] = arr[i- 1]
. - Insert the new element at the first position by setting
arr[0] = element_to_add
. - Finally, print the modified array.
Note: If the array is not large enough to accommodate the new element, then we might need to create a new array with sufficient space and then copy all the elements of the old array to the new array along with the new element at its position. If the old array was static, then we cannot free its space. If the old array was dynamic, then we can use the delete[] to free the occupied memory.
C++ Program to Add an Element in the Array at the Beginning
The below program demonstrates how we can add an element at the beginning of an array in C++.
// C++ program to demonstrate how to add an element at the
// beginning of an array
#include <iostream>
using namespace std;
int main()
{
// Original array with some unused space at the end
int arr[6] = { 10, 20, 30, 40, 50 };
int n = 5; // Number of elements in the array
cout << "Original Array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
// Element to add
int element_to_add = 5;
// Shift all elements one position to the right
for (int i = n; i > 0; i--) {
arr[i] = arr[i - 1];
}
// Add the element at the beginning of the array
arr[0] = element_to_add;
// Print the array
cout << "Updated Array: ";
for (int i = 0; i <= n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
Output
Original Array: 10 20 30 40 50 Updated Array: 5 10 20 30 40 50
Time Complexity: O(n), where n is the number of elements in the array.
Auxilliary Space: O(1), if the array has space enough to store new element. O(n) if we need to declare new array.
Note: It is preferred to use std::vector to manage a dynamic array in C++ which allows elements to be efficiently added at any position, including the beginning.