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.
DSA Java
for (int i = arr.length - 1; i > [1]; i--) { arr[i] = arr[i - 1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting the loop from index 1 instead of 0.
Using the wrong loop condition that skips shifting the first element.
✗ Incorrect
We start shifting elements from the last index down to index 1 to make space at index 0 for the new element.
2fill in blank
mediumComplete the code to assign the new value at the beginning of the array after shifting.
DSA Java
arr[[1]] = newValue;Attempts:
3 left
💡 Hint
Common Mistakes
Assigning the new value to the last index instead of the first.
Using the newValue variable as an index.
✗ Incorrect
The new value should be placed at index 0, which is the beginning of the array.
3fill in blank
hardFix the error in the loop condition to correctly shift elements for insertion at the beginning.
DSA Java
for (int i = arr.length - 1; i [1] 0; i--) { arr[i] = arr[i - 1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' causes an index out of bounds error.
Using '<' or '<=' causes the loop to not run correctly.
✗ Incorrect
We want to shift elements while i is greater than 0 to avoid accessing invalid index -1.
4fill in blank
hardFill both blanks to create a method that inserts a value at the beginning of an array by shifting elements.
DSA Java
public static void insertAtBeginning(int[] arr, int newValue) {
for (int i = arr.length - 1; i [1] 0; i--) {
arr[i] = arr[i [2] 1];
}
arr[0] = newValue;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '+' instead of '-' in the index calculation.
Using '>=' in the loop condition causing errors.
✗ Incorrect
The loop runs while i > 0, and elements are shifted by assigning arr[i] = arr[i - 1].
5fill in blank
hardFill all three blanks to complete the method that inserts a value at the beginning and prints the array.
DSA Java
public static void insertAndPrint(int[] arr, int newValue) {
for (int i = arr.length - 1; i [1] 0; i--) {
arr[i] = arr[i [2] 1];
}
arr[[3]] = newValue;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '+ 1' instead of '- 1' when shifting elements.
Assigning newValue to the wrong index.
Incorrect loop condition causing errors.
✗ Incorrect
The loop condition is i > 0, elements shift by arr[i] = arr[i - 1], and newValue is assigned at index 0.
