![]() |
VOOZH | about |
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++.
Input:
original_array = {10, 20, 30, 40, 50}
element_to_add = 5
Output:
updated_array: 5 10 20 30 40 50
If we have a large enough 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.
arr[i] = arr[i- 1]. arr[0] = element_to_add.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.
The below program demonstrates how we can add an element at the beginning of an array in C++.
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 to manage a dynamic array in C++ which allows elements to be efficiently added at any position, including the beginning.