Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 12 / 68

Recursive Functions

In this lesson you will learn how to write a recursive function in C# and understand how a function can call itself. This is for anyone searching for "C# recursive function how to use".

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

The sample code has Factorial call itself in the form n * Factorial(n - 1) to compute the factorial of 5. The stopping condition if (n <= 1) return 1; is what makes the chain of calls come to an end.

A common stumbling block for beginners is forgetting that stopping condition. Without one, the function calls itself forever and the program crashes.

In real-world development, keep in mind that every recursive call stacks a new execution context, so recursion that goes too deep consumes a great deal of memory.

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

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