Menu
CoddyTech

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 step

It has two parts:

  • The base case answers without calling the function again: the sum up to 0 is 0.
  • 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 icon

Challenge

Easy

The 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
0

Try 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
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