using System; class Program { static int Factorial(int n) { if (n == 0) return 1; return n * Factorial(n - 1); } static void Main() { Console.WriteLine(Factorial(4)); } }
The function calls itself with decreasing values until it reaches 0, then multiplies back up.
4! = 4 * 3 * 2 * 1 = 24.
Recursion is ideal for problems with nested or hierarchical data, like folders inside folders.
Loops can do simple repetition but struggle with unknown levels of nesting.
using System; class Program { static int Fib(int n) { if (n == 0) return 0; if (n == 1) return 1; return Fib(n - 1) + Fib(n - 2); } static void Main() { Console.WriteLine(Fib(-1)); } }
The function does not handle negative inputs properly.
Calling Fib(-1) causes infinite recursion because the base case is never reached.
using System; class Program { static void PrintFolders(string folder, int depth) { Console.WriteLine(new string('-', depth) + folder); if (folder == "root") { PrintFolders("sub1", depth + 1); PrintFolders("sub2", depth + 1); } else if (folder == "sub1") { PrintFolders("sub1a", depth + 1); } } static void Main() { PrintFolders("root", 0); } }
The method prints the folder name with dashes equal to depth.
It calls subfolders recursively in order.
Recursion naturally handles problems with unknown or dynamic nesting, like trees or nested folders.
Loops require fixed or known repetition counts.
