C# Recursion Tutorial | Easy Recursion Example in C#
Hey buddy, have you ever seen a mirror inside a mirror? 🤯
Imagine you’re standing between two mirrors 🪞, and you see endless reflections of yourself. That’s kind of how recursion works in programming!
A recursive function is a function that calls itself until a certain condition is met. It’s like asking yourself a question over and over until you get the right answer. Pretty cool, right? 😃
But wait… does this mean infinite loops? Nope! There’s always a way to stop recursion, or else your program will crash! 😅 Don’t worry, I’ll make it super easy for you. Let’s go! 🚀
What You Are Going to Learn in This Lesson
✔️ What recursion is and how it works.
✔️ A real-world example to make it simple.
✔️ The syntax of recursion in C#.
✔️ A few C# Recursion Examples with complete code and output.
✔️ When to use recursion (and when NOT to!).
What is Recursion in C#?
Recursion means a function calls itself to solve a problem. Each time the function calls itself, it gets closer to the final answer.
Think of it like peeling an onion 🧅. Each layer gets you closer to the center (the solution).
Syntax of Recursion in C#
void RecursiveFunction()
{
if (condition) // Base case (stopping condition)
{
return;
}
RecursiveFunction(); // Recursive call (calling itself)
}
How it Works?
1️⃣ The function checks a condition (base case).
2️⃣ If the condition is met, it stops (to prevent infinite recursion).
3️⃣ Otherwise, it calls itself again.
Recursion Example C# (Basic One First!)
Let’s start with a simple example before moving to a real-world scenario.
1️⃣ Printing Numbers Using Recursion
using System;
class Program
{
static void PrintNumbers(int num)
{
if (num == 0) // Base condition (stopping point)
return;
Console.WriteLine(num);
PrintNumbers(num - 1); // Recursive call
}
static void Main()
{
PrintNumbers(5);
}
}
Output:
5
4
3
2
1
How Does It Work?
- The function PrintNumbers(5) prints
5
, then calls PrintNumbers(4). - It keeps calling itself with
num - 1
untilnum
becomes0
. - When
num == 0
, the function stops (base case).
So, it’s like counting backward using recursion! 😃
2️⃣ Real-World Example: Factorial Calculation! 🎲
Ever played with factorials? The factorial of a number n
is:
n! = n × (n-1) × (n-2) × ... × 1
Let’s calculate it recursively!
using System;
class Program
{
static int Factorial(int n)
{
if (n == 1) // Base case
return 1;
return n * Factorial(n - 1); // Recursive call
}
static void Main()
{
Console.Write("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
int result = Factorial(num);
Console.WriteLine($"Factorial of {num} is {result}");
}
}
Output:
Enter a number: 5
Factorial of 5 is 120
How Does It Work?
Factorial(5)
callsFactorial(4)
, which callsFactorial(3)
, and so on…- When it reaches
Factorial(1)
, it stops. - Then, all functions return their values back up and multiply them.
So, it’s like unfolding a puzzle piece by piece! 🧩
3️⃣ Find the Sum of Digits Using Recursion
Let’s say you have a number 1234. You want to find the sum of its digits (1+2+3+4 = 10).
Here’s how you do it with recursion:
using System;
class Program
{
static int SumOfDigits(int num)
{
if (num == 0) // Base case
return 0;
return (num % 10) + SumOfDigits(num / 10); // Recursive call
}
static void Main()
{
Console.Write("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
int result = SumOfDigits(num);
Console.WriteLine($"Sum of digits: {result}");
}
}
Output:
Enter a number: 1234
Sum of digits: 10
How It Works?
1234 % 10 = 4
(takes the last digit).- Calls
SumOfDigits(123)
, thenSumOfDigits(12)
, thenSumOfDigits(1)
, thenSumOfDigits(0)
. - When it reaches
0
, it stops and adds up all the digits.
Pretty neat, huh? 😃
4️⃣ Fibonacci Series Using Recursion
The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13…
Each number is the sum of the previous two numbers.
Here’s how you can generate Fibonacci numbers recursively:
using System;
class Program
{
static int Fibonacci(int n)
{
if (n <= 1) // Base case
return n;
return Fibonacci(n - 1) + Fibonacci(n - 2); // Recursive calls
}
static void Main()
{
Console.Write("Enter the position: ");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"Fibonacci number at position {n} is {Fibonacci(n)}");
}
}
Output:
Enter the position: 6
Fibonacci number at position 6 is 8
How It Works?
Fibonacci(6)
callsFibonacci(5) + Fibonacci(4)
, which calls more functions…- It keeps breaking down until it reaches Fibonacci(1) or Fibonacci(0), which are base cases.
When Should You Use Recursion?
✅ When a problem is naturally recursive (like factorial, Fibonacci, tree traversal).
✅ When breaking down the problem into smaller problems makes sense.
However…
❌ Don’t use it if it causes too many function calls, as it may lead to stack overflow.
❌ Sometimes, loops (for
, while
) are better and faster than recursion.
Conclusion
Congrats, my friend! 🎉 You just learned C# Recursion in an easy way! 😃
Recursion is like a function calling itself until it reaches the answer. It’s useful for solving problems step by step but must be used wisely to avoid infinite loops.
Got stuck? No worries! Drop a comment, and we’ll be happy to help! 😊
Next What?
Okay, you’ve mastered recursion! Now, it’s time to learn Encapsulation and Abstraction in C#! 🏆
These concepts will help you organize your code better and make it secure. Stay tuned! 🚀