Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a value at the middle index of the array.
DSA C#
int[] arr = {1, 2, 4, 5};
int middle = arr.Length / 2;
int value = 3;
int[] result = new int[arr.Length + 1];
for (int i = 0; i < middle; i++) {
result[i] = arr[i];
}
result[middle] = [1];
for (int i = middle; i < arr.Length; i++) {
result[i + 1] = arr[i];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using arr[middle] instead of value inserts the old element again.
Using middle as a value inserts the index, not the value.
✗ Incorrect
We insert the new value at the middle index, so we assign 'value' to result[middle].
2fill in blank
mediumComplete the code to calculate the middle index for insertion.
DSA C#
int[] arr = {10, 20, 30, 40, 50};
int middle = [1];
// middle should be the index to insert in the middleAttempts:
3 left
💡 Hint
Common Mistakes
Using arr.Length - 1 gives the last index, not the middle.
Using arr.Length + 1 is out of bounds.
✗ Incorrect
The middle index is the length divided by 2, which gives the center position.
3fill in blank
hardFix the error in the loop that copies elements after the middle index.
DSA C#
for (int i = middle; i < arr.Length; i++) { result[i [1] 1] = arr[i]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' shifts elements left, overwriting data.
Using '*' or '/' causes invalid indexing.
✗ Incorrect
We add 1 to the index in result to shift elements right after insertion.
4fill in blank
hardFill both blanks to create a loop that copies elements before the middle index.
DSA C#
for (int i = 0; i [1] middle; i++) { result[i] = arr[2]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' copies one extra element.
Using '[middle]' copies the wrong element repeatedly.
✗ Incorrect
The loop runs while i is less than middle, copying arr[i] to result[i].
5fill in blank
hardFill all three blanks to create a method that inserts a value at the middle index of an array.
DSA C#
public static int[] InsertMiddle(int[] arr, int value) {
int middle = arr.Length [1] 2;
int[] result = new int[arr.Length [2] 1];
for (int i = 0; i [3] middle; i++) {
result[i] = arr[i];
}
result[middle] = value;
for (int i = middle; i < arr.Length; i++) {
result[i + 1] = arr[i];
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' for new array size causes too small array.
Using '<=' in loop copies one extra element.
✗ Incorrect
Divide length by 2 for middle, add 1 for new array size, and loop while i < middle.
