Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to extract the first three elements from the array.
Bash Scripting
arr=(apple banana cherry date)
slice=(${arr[@]:[1]:3})
echo "${slice[@]}" Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting the slice at 1 will skip the first element.
Using a length other than 3 will give wrong number of elements.
✗ Incorrect
In bash, array slicing starts at index 0. To get the first three elements, start at 0 and take 3 elements.
2fill in blank
mediumComplete the code to extract elements starting from the second element to the end.
Bash Scripting
arr=(red green blue yellow)
slice=(${arr[@]:[1])
echo "${slice[@]}" Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 0 extracts the whole array.
Starting at 2 skips the second element.
✗ Incorrect
Starting at index 1 extracts elements from the second element to the end.
3fill in blank
hardFix the error in the code to correctly slice the array from the third element, taking two elements.
Bash Scripting
arr=(one two three four five)
slice=(${arr[@]:[1]:2})
echo "${slice[@]}" Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 3 starts from the fourth element, not third.
Using index 1 starts from the second element.
✗ Incorrect
Index 2 corresponds to the third element in the array, so slicing from 2 with length 2 extracts the third and fourth elements.
4fill in blank
hardFill both blanks to slice the array from the second element and take three elements.
Bash Scripting
arr=(cat dog bird fish horse)
slice=(${arr[@]:[1]:[2])
echo "${slice[@]}" Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 2 skips the second element.
Taking 2 elements returns fewer than needed.
✗ Incorrect
Start at index 1 (second element) and take 3 elements to get dog, bird, fish.
5fill in blank
hardComplete the code to extract the last three elements from the array using a negative index.
Bash Scripting
arr=(apple bat cherry dog elephant fox)
slice=(${arr[@]:[1])
echo "${slice[@]}" Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 3 extracts from index 3 to end, which happens to be the same here, but positive indexes count from the start.
Using 0 extracts the entire array.
Using -1 extracts only the last element.
✗ Incorrect
Using a negative index -3 in the slice extracts the last three elements: dog elephant fox.