Recursive Functions Part 1
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 57 of 78.
A recursive function is a function that calls itself. Each call solves a smaller version of the problem, until the problem is small enough to answer directly.
This function adds the whole numbers from 1 to n:
func sum_to_n(n: int) -> int:
if n == 0: # base case
return 0
return n + sum_to_n(n - 1) # recursive stepIt has two parts:
- The base case answers without calling the function again: the sum up to
0is0. - The recursive step calls the function with a smaller value,
n - 1, and builds its answer from the result.
sum_to_n(3) is 3 + sum_to_n(2), which is 3 + 2 + sum_to_n(1), which is 3 + 2 + 1 + sum_to_n(0). The base case returns 0, and the waiting calls finish one by one: the result is 6.
Every recursive step must move closer to the base case. Without a base case, or with a step like n + 1 that never reaches it, the function keeps calling itself. Godot allows about 1,000 calls inside each other and then stops the program with an error.
Challenge
EasyThe program reads a whole number n (0 or more) and calls count_down(n).
Below _ready(), write the recursive function count_down with one parameter. It prints every number from its argument down to 0, one per line. Use no loop: the function prints its number and calls itself with the next smaller one.
For the input 3, the output is:
3
2
1
0Try it yourself
extends Node
func _ready():
var n := int(OS.read_string_from_stdin())
count_down(n)
# Write the recursive function count_down(n) below
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