Shift right + insert 5 at start = [5,10,20,30,40] [OK]
Hint: Trace shifts from end, then insert new element at start [OK]
Common Mistakes:
Not shifting last element correctly
Overwriting elements during shift
Forgetting to insert new element at index 0
4. Identify the error in this code snippet that tries to insert an element at the beginning of an array:
int arr[5] = {1, 2, 3, 4, 0};
int n = 4;
int new_element = 0;
for(int i = 0; i < n; i++) {
arr[i+1] = arr[i];
}
arr[0] = new_element;
medium
A. Loop direction causes overwriting of elements during shift.
B. Array size is too small to insert new element.
C. New element is assigned after shifting elements.
D. Loop condition should be i <= n instead of i < n.
Solution
Step 1: Analyze loop direction and assignments
Loop shifts elements from start to end, causing arr[i+1] to overwrite arr[i+1] before it is copied.
Step 2: Correct approach is to shift from end to start
Shifting from end to start prevents overwriting original values during shift.
Final Answer:
Loop direction causes overwriting of elements during shift. -> Option A
Quick Check:
Shift must go backward to avoid overwrite [OK]
Hint: Shift elements backward to avoid overwriting [OK]
Common Mistakes:
Shifting forward overwrites data
Ignoring array size limits
Incorrect loop boundaries
5. Given an array int arr[7] = {2, 4, 6, 8, 10, 0, 0}; with n = 5 elements, write the steps to insert 1 at the beginning and then 0 at the beginning again. What will be the final array content?
hard
A. [0, 1, 2, 4, 6, 8, 10]
B. [0, 1, 2, 4, 6, 8]
C. [0, 1, 2, 4, 6, 8, 10, 0]
D. [1, 0, 2, 4, 6, 8]
Solution
Step 1: Insert 1 at beginning
Shift elements right: arr[5]=arr[4]=10, arr[4]=arr[3]=8, arr[3]=arr[2]=6, arr[2]=arr[1]=4, arr[1]=arr[0]=2; then arr[0]=1. Array: [1, 2, 4, 6, 8, 10]
Step 2: Insert 0 at beginning
Shift elements right again: arr[6]=arr[5]=10, arr[5]=arr[4]=8, arr[4]=arr[3]=6, arr[3]=arr[2]=4, arr[2]=arr[1]=2, arr[1]=arr[0]=1; then arr[0]=0. Array: [0, 1, 2, 4, 6, 8, 10]
Final Answer:
[0, 1, 2, 4, 6, 8, 10] -> Option A
Quick Check:
Two shifts + inserts = [0,1,2,4,6,8,10] [OK]
Hint: Shift right twice, insert each new element at index 0 [OK]
Common Mistakes:
Not updating array size after insertions
Overwriting elements during second insertion
Assuming array can hold more than 6 elements
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.