Ad space (banner)
๐Ÿ”ทVB.NET Lessons
Lesson 12 / 68

Recursive functions

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

A recursive function is one that calls itself. The basic idea is breaking a large problem into one slightly smaller version of the same problem. It suits regular, repeating calculations such as a factorial.

In the sample code, a Factorial function calls itself as n * Factorial(n - 1) to calculate 5 factorial. The finishing condition If n <= 1 Then Return 1 is what stops the calls going on forever.

A common early stumble is forgetting that finishing condition. Without one the calls continue until you get a stack overflow, so decide the finishing condition before writing anything else.

Recursion produces concise code but can be slow when the call count is high, so in practice it is sometimes rewritten as a loop. Walking a tree or a folder hierarchy, though, fits recursion naturally.

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

๐Ÿงช This site can't compile or run VB.NET 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)