Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a recursive function that prints numbers from n down to 1.
Bash Scripting
print_numbers() {
if [ $1 -le 0 ]; then
return
fi
echo $1
print_numbers [1]
}
print_numbers 5 Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 + 1 which increases the number and causes infinite recursion.
Not using arithmetic expansion, causing syntax errors.
✗ Incorrect
The function calls itself with the argument decreased by 1 to count down.
2fill in blank
mediumComplete the code to calculate the factorial of a number recursively.
Bash Scripting
factorial() {
if [ $1 -le 1 ]; then
echo 1
else
local prev=$(factorial [1])
echo $(( $1 * prev ))
fi
}
factorial 5 Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 - 1 without arithmetic expansion causes errors.
Increasing the argument instead of decreasing it.
✗ Incorrect
The function calls itself with the argument decreased by 1 to compute factorial.
3fill in blank
hardFix the error in the recursive function that sums numbers from 1 to n.
Bash Scripting
sum_to_n() {
if [ $1 -eq 1 ]; then
echo 1
else
local prev=$(sum_to_n [1])
echo $(( $1 + prev ))
fi
}
sum_to_n 5 Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Increasing the argument causes infinite recursion.
Not using arithmetic expansion leads to syntax errors.
✗ Incorrect
The function must call itself with the argument decreased by 1 to sum correctly.
4fill in blank
hardFill both blanks to create a recursive function that computes the nth Fibonacci number.
Bash Scripting
fib() {
if [ $1 -le 1 ]; then
echo $1
else
local a=$(fib [1])
local b=$(fib [2])
echo $(( a + b ))
fi
}
fib 6 Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 - 1 without $(( )) causes errors.
Mixing arithmetic and string subtraction.
✗ Incorrect
Fibonacci of n is sum of fib(n-1) and fib(n-2), using arithmetic expansion.
5fill in blank
hardFill all three blanks to create a recursive function that reverses a string.
Bash Scripting
reverse() {
if [ -z "$1" ]; then
echo ""
else
local first=${1:0:1}
local rest=${1:1}
local rev_rest=$(reverse [1])
echo "${rev_rest}[2]${first}[3]"
fi
}
reverse "hello" Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the first character instead of the rest in recursive call.
Adding spaces between characters when reversing.
✗ Incorrect
The function calls reverse with the rest of the string, then appends the first character at the end.