ZetCode

Julia Recursion Tutorial

last modified November 18, 2026

Recursion is a technique in which a function solves a problem by calling itself on a smaller version of the same problem. It is a natural fit for tasks that are defined in terms of themselves, such as factorials, tree traversal, and many sorting algorithms. This tutorial explains how recursive functions are built and what pitfalls to watch for.

Every recursive function needs a base case that stops the process and a recursive case that moves toward it. We also look at tail recursion, memoization, stack depth, and mutual recursion. The Julia functions article introduces function definitions; here we focus on functions that call themselves. All examples were verified with Julia 1.13.4.

Base Case and Recursive Case

A recursive function has two parts. The base case returns a result directly, without another call; the recursive case calls the same function with a smaller argument. Factorial is the classic example: the factorial of zero is one, and the factorial of n is n times the factorial of n minus one.

main.jl
function factorial(n::Int)
    if n == 0
        return 1
    else
        return n * factorial(n - 1)
    end
end

println(factorial(0))
println(factorial(5))
println(factorial(10))

The condition n == 0 is the base case; it stops the chain of calls. Otherwise the function returns n * factorial(n - 1), which is the recursive case. The annotation n::Int restricts the argument to an integer. The results are 1, 120, and 3628800.

$ julia main.jl
1
120
3628800

Fibonacci Sequence

The Fibonacci sequence starts with 0 and 1, and each later term is the sum of the two before it. This definition translates almost directly into a recursive function with two base cases.

main.jl
function fib(n::Int)
    if n < 2
        return n
    end
    return fib(n - 1) + fib(n - 2)
end

println(join([fib(i) for i in 0:10], " "))

For n equal to 0 or 1 the function returns n itself. For larger values it makes two recursive calls. The printed sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. This version is short but wasteful: the same values are computed many times, a problem addressed by memoization below.

$ julia main.jl
0 1 1 2 3 5 8 13 21 34 55

Following the Calls

It helps to see when each call begins and ends. This version prints a line on entry and another on exit, with the base case reporting its own stop.

main.jl
function countdown(n::Int)
    println("enter ", n)
    if n == 0
        println("done")
        return
    end
    countdown(n - 1)
    println("exit ", n)
end

countdown(3)

The calls go down from 3 to 0 before anything unwinds. Once the base case prints done, each call resumes in reverse order and prints its exit line. This pattern — descend, then return — is why recursion is well suited to nested structures such as trees.

$ julia main.jl
enter 3
enter 2
enter 1
enter 0
done
exit 1
exit 2
exit 3

Tail Recursion

A recursive call is in tail position when it is the last operation a function performs. Here the running product is carried in an accumulator, so the call to fact_tail is the final expression rather than a multiplication that happens after the call returns.

main.jl
function fact_tail(n::Int, acc::Int=1)
    if n <= 1
        return acc
    end
    return fact_tail(n - 1, acc * n)
end

println(fact_tail(6))
println(fact_tail(10))

The accumulator multiplies the result into itself at each step, so no pending work waits on the stack. Julia does not guarantee tail-call elimination, however, so a very deep tail recursion can still exhaust the stack; write an iterative loop when depth may be large.

$ julia main.jl
720
3628800

Memoization

Memoization means caching the results of expensive calls so that repeated subproblems are computed only once. A dictionary is a convenient cache, keyed by the function argument.

main.jl
const cache = Dict{Int,Int}()

function fib_memo(n::Int)
    if n < 2
        return n
    end
    if haskey(cache, n)
        return cache[n]
    end
    result = fib_memo(n - 1) + fib_memo(n - 2)
    cache[n] = result
    return result
end

println(fib_memo(40))
println(length(cache))

Before recursing, the function checks whether n is already in the cache and returns the stored value if so. Otherwise it computes the result and stores it. The 40th Fibonacci number is 102334155, and the cache holds 39 computed entries — without memoization this would take vastly more calls. Dictionaries are introduced in Julia dictionaries.

$ julia main.jl
102334155
39

Stack Depth and StackOverflowError

Each active function call occupies space on the call stack. A recursive function that never reaches its base case keeps adding frames until the stack is full, and Julia raises a StackOverflowError.

main.jl
function forever(n::Int)
    return forever(n + 1)
end

try
    forever(0)
catch e
    println(typeof(e))
end

The function forever has no base case, so it calls itself without end. The try/catch block captures the resulting error and prints its type. In real code, make sure every recursive path moves toward a base case, and prefer iteration when the depth can be very large. See Julia exceptions for more on error handling.

$ julia main.jl
StackOverflowError

Mutual Recursion

Two functions are mutually recursive when each calls the other. The classic example decides whether a number is even or odd by reducing it by one and asking the opposite question at each step.

main.jl
function iseven(n::Int)
    n == 0 ? true : isodd(n - 1)
end

function isodd(n::Int)
    n == 0 ? false : iseven(n - 1)
end

println(iseven(10), " ", isodd(10))
println(iseven(7), " ", isodd(7))

Both functions use zero as their base case: zero is even, not odd. For any other value, iseven asks isodd about the previous number and vice versa, alternating until zero is reached. The ternary operator condition ? a : b keeps each body to a single line.

$ julia main.jl
true false
false true

Other Recursive Patterns

Recursion is not limited to teaching examples. Euclid's algorithm for the greatest common divisor and exponentiation by repeated multiplication both have short recursive definitions.

main.jl
function mygcd(a::Int, b::Int)
    b == 0 ? a : mygcd(b, a % b)
end

function power(b::Int, e::Int)
    e == 0 ? 1 : b * power(b, e - 1)
end

println(mygcd(48, 18))
println(power(2, 10))

The greatest common divisor of 48 and 18 is 6. The % operator gives the remainder, and the pair shrinks until the second argument is zero. power(2, 10) multiplies 2 by itself ten times to produce 1024. Both functions reduce the problem on every call, which is the essential property of a terminating recursion.

$ julia main.jl
6
1024

Best Practices for Recursion

Recursive code is clearer when a few guidelines are followed.

Source

Julia Functions documentation

Julia StackOverflowError documentation

In this article we have worked with recursion in Julia: base and recursive cases, factorial and Fibonacci, following the call chain, tail recursion, memoization, stack overflow, and mutual recursion. Function definitions are covered in Julia functions, control flow in Julia control flow, and caching with dictionaries in Julia dictionaries.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Julia tutorials.