VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/recursion-in-c-sharp/

⇱ Recursion in C# - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Recursion in C#

Last Updated : 19 Mar, 2026

Recursion is a programming technique where a method calls itself repeatedly until a specific base condition is met. A method that performs this behavior is called a recursive method, and each self-call is known as a recursive call. Example:


Output
Hello
Hello
Hello
Hello
Hello

The method PrintHello(n) prints "Hello" and calls itself with n-1 until n == 0. When the base condition is reached, recursion stops.

Recursive Method

A method that calls itself is known as a recursive method. It breaks a problem into smaller subproblems of the same type.

A recursive method must have:

  • Base Condition: Stops recursion
  • Recursive Case: Calls the method again

General Structure

How Recursion Works?

When a method calls itself:

  • Each call is stored in stack memory (call stack)
  • New calls are added (stack grows)
  • When base condition is reached: calls start returning (stack shrinks)

The following example demonstrates both the descending phase (going deeper into recursion) and the ascending phase (returning back from recursion):

Output:

F(3)'s Stack Frame Pushed
F(2)'s Stack Frame Pushed
F(1)'s Stack Frame Pushed
F(1)'s Stack Frame Removed
F(1)'s Stack Frame Pushed
F(1)'s Stack Frame Removed
F(2)'s Stack Frame Removed
F(2)'s Stack Frame Pushed
F(1)'s Stack Frame Pushed
F(1)'s Stack Frame Removed
F(1)'s Stack Frame Pushed
F(1)'s Stack Frame Removed
F(2)'s Stack Frame Removed
F(3)'s Stack Frame Removed

Below is the illustration of function call stack of the above code:

Applications of Recursion

Recursion is commonly used in:

  • Factorial and Fibonacci problems
  • Searching & Sorting (Binary Search, QuickSort)
  • Tree and Graph Traversal
  • Backtracking problems
  • Dynamic Programming
Advantages of RecursionDisadvantages of Recursion
Code is short and cleanHigher memory usage
Easy to solve complex problemsCan be slower than iteration
Natural fit for tree/graph problemsRisk of stack overflow
Improves code readabilityHarder to debug
Comment
Article Tags:

Explore