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:
- The base case says when to stop.
- 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 stepfactorial(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"))ollehChallenge
EasyWrite a recursive function named fibonacci that takes a positive whole number n and returns the nth Fibonacci number:
fibonacci(1)is0fibonacci(2)is1- for
n > 2,fibonacci(n)isfibonacci(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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter10Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested Array2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler