Ad space (banner)
๐ŸŸฃJulia Lessons
Lesson 12 / 68

Recursive functions

This lesson covers writing a recursive function in Julia, with the aim of understanding how a function can call itself.

A recursive function is one that calls itself. It suits work that repeats the same pattern of calculation, such as "n! = n ร— (n-1)!".

In the sample code, factorial_j calls itself as n * factorial_j(n - 1) to calculate 5 factorial. The finishing condition if n <= 1 return 1 end is what makes the calls stop somewhere.

A common early stumble is forgetting the finishing condition. Without one, the function calls itself forever and the program dies.

In professional work, deep recursion consumes a great deal of stack, so it is worth considering whether a loop would do instead.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Julia directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)