0
0
Bash Scriptingscripting~10 mins

Recursive functions in Bash Scripting - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A$(( $1 + 1 ))
B$1 + 1
C$(( $1 - 1 ))
D$1 - 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 + 1 which increases the number and causes infinite recursion.
Not using arithmetic expansion, causing syntax errors.
2fill in blank
medium

Complete 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'
A$1 + 1
B$1 - 1
C$(( $1 + 1 ))
D$(( $1 - 1 ))
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 - 1 without arithmetic expansion causes errors.
Increasing the argument instead of decreasing it.
3fill in blank
hard

Fix 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'
A$(( $1 - 1 ))
B$(( $1 + 1 ))
C$1 + 1
D$1 - 1
Attempts:
3 left
💡 Hint
Common Mistakes
Increasing the argument causes infinite recursion.
Not using arithmetic expansion leads to syntax errors.
4fill in blank
hard

Fill 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'
A$(( $1 - 1 ))
B$1 - 1
C$(( $1 - 2 ))
D$1 - 2
Attempts:
3 left
💡 Hint
Common Mistakes
Using $1 - 1 without $(( )) causes errors.
Mixing arithmetic and string subtraction.
5fill in blank
hard

Fill 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'
A"$rest"
B"$first"
C""
D" "
Attempts:
3 left
💡 Hint
Common Mistakes
Using the first character instead of the rest in recursive call.
Adding spaces between characters when reversing.