Lesson 7 of 15
Recursion
Recursion
A function can call itself. The key is a base case that stops the recursion:
def factorial(n: Int): Int =
if (n <= 1) 1 else n * factorial(n - 1)
println(factorial(5)) // 120
Fibonacci
def fib(n: Int): Int =
if (n <= 1) n else fib(n - 1) + fib(n - 2)
println(fib(7)) // 13
Your Task
Write a recursive function power(base: Int, exp: Int): Int that returns base raised to exp. Assume exp >= 0. Base case: power(x, 0) = 1.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.