Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert an element at the beginning of the array by shifting elements right.
DSA C++
for (int i = n; i > [1]; i--) { arr[i] = arr[i - 1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting the loop at i > 1 instead of i > 0 causes the first element not to shift.
Using i >= 0 causes out-of-bound errors.
✗ Incorrect
We start shifting elements from the end (index n) down to index 1, moving each element one position right. The loop stops when i > 0, so the first element at index 0 is free for insertion.
2fill in blank
mediumComplete the code to assign the new element at the beginning of the array after shifting.
DSA C++
arr[[1]] = new_element;Attempts:
3 left
💡 Hint
Common Mistakes
Assigning the new element at index 1 or n causes incorrect placement.
Using n or n-1 places the element beyond the intended start.
✗ Incorrect
After shifting elements right, the first position at index 0 is free to hold the new element.
3fill in blank
hardFix the error in the loop condition to correctly shift elements right for insertion at the beginning.
DSA C++
for (int i = n; i [1] 0; i--) { arr[i] = arr[i - 1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '<=' causes the loop to run incorrectly or infinitely.
Using '>=' causes out-of-bound access at i=0.
✗ Incorrect
The loop must run while i is greater than 0 to avoid accessing arr[-1]. Using '>' ensures safe shifting.
4fill in blank
hardFill both blanks to complete the function that inserts an element at the beginning of the array.
DSA C++
void insertAtBeginning(int arr[], int& n, int new_element) {
for (int i = n; i > [1]; i--) {
arr[i] = arr[i - 1];
}
arr[[2]] = new_element;
n++;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using different indices for shifting and assignment causes data overwrite.
Incorrect loop condition leads to out-of-bound errors.
✗ Incorrect
The loop shifts elements while i > 0, freeing index 0 for the new element. Then the new element is assigned at index 0.
5fill in blank
hardFill all three blanks to create a function that inserts an element at the beginning and updates the size.
DSA C++
void insertAtBeginning(int arr[], int& [1], int [2]) { for (int i = [3]; i > 0; i--) { arr[i] = arr[i - 1]; } arr[0] = [2]; [1]++; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names causes compilation errors.
Not passing size by reference prevents updating the array size.
✗ Incorrect
The function takes the array size 'n' by reference to update it, the new element to insert, and shifts elements from index n down to 1. Then it inserts the new element at index 0 and increments n.
