#include <iostream> using namespace std; int main() { int arr[5] = {2, 4, 6, 8}; int n = 4; // current number of elements int x = 10; // element to insert at beginning for (int i = n; i > 0; i--) { arr[i] = arr[i - 1]; } arr[0] = x; n++; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0; }
The code shifts all elements one position to the right starting from the end, then inserts the new element at the beginning (index 0). The array after insertion is: 10 2 4 6 8.
Since arrays have fixed positions, to insert at the beginning, all elements must move one step right to free index 0 for the new element.
#include <iostream> using namespace std; int main() { int arr[4] = {1, 2, 3, 4}; int n = 4; int x = 0; for (int i = n; i > 0; i--) { arr[i] = arr[i - 1]; } arr[0] = x; n++; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0; }
The loop runs from i = n down to 1, so when i = n (which is 4), arr[i] = arr[i - 1] tries to access arr[4] which is out of bounds for an array of size 4.
#include <iostream> using namespace std; int main() { int arr[6] = {5, 6, 7, 8}; int n = 4; // Insert 3 at beginning for (int i = n; i > 0; i--) { arr[i] = arr[i - 1]; } arr[0] = 3; n++; // Insert 1 at beginning for (int i = n; i > 0; i--) { arr[i] = arr[i - 1]; } arr[0] = 1; n++; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0; }
First insertion adds 3 at the start: 3 5 6 7 8. Second insertion adds 1 at the start, shifting all right: 1 3 5 6 7 8.
Inserting at the beginning requires shifting all existing elements one position right, which takes time proportional to n.
