Menu
CoddyTech

Recursive Functions Part 2

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 58 of 78.

Every recursive function has the same two parts:

  1. The base case says when to stop.
  2. The recursive step calls the function with a smaller input.

The factorial of n is n * (n - 1) * ... * 1, so the factorial of n is n times the factorial of n - 1:

func factorial(n: int) -> int:
	if n == 1: # base case
		return 1
	return n * factorial(n - 1) # recursive step

factorial(5) calls factorial(4), which calls factorial(3), down to factorial(1), which returns 1. On the way back, each call multiplies: the result is 120.

A smaller input does not have to be a smaller number. A shorter string works too. This function reverses a string:

func reverse_text(text: String) -> String:
	if text.length() <= 1: # base case
		return text
	return reverse_text(text.substr(1)) + text[0]

text.substr(1) is the string without its first character. The function reverses that shorter string and adds the first character at the end. A string of zero or one character is already reversed, so it is the base case.

print(reverse_text("hello"))
olleh
challenge icon

Challenge

Easy

Write a recursive function named fibonacci that takes a positive whole number n and returns the nth Fibonacci number:

  • fibonacci(1) is 0
  • fibonacci(2) is 1
  • for n > 2, fibonacci(n) is fibonacci(n - 1) + fibonacci(n - 2)

For example, fibonacci(6) returns 5 (the sequence starts 0, 1, 1, 2, 3, 5).

The tests call fibonacci() themselves. Do not call it, and do not print anything.

Try it yourself

func fibonacci(n: int):
	# Write code here
	pass
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler