Lesson 5
Simple Recursion in Practice
Lesson Overview

The topic of our lesson today is Simple Recursion in Practice. As you may already know, recursion is a fundamental concept in computer science and an essential skill for any serious programmer to master. Using recursion can simplify code and make it easier to understand, although it can sometimes be hard to grasp. Essentially, it is a method where the solution to a problem is based on solving smaller instances of the same problem.

Quick Example

Let's quickly examine a factorial calculation, probably the most common and simple example of recursion. In math, the factorial of a number n is the product of all positive integers less than or equal to n. It sounds complicated, but if we think about it, the factorial of n can be calculated as the multiplication of the number n and the factorial of n - 1. So, in C#, we can write a recursive function that calculates the factorial of a number. It will multiply the number by the factorial of number - 1 until it reaches 0. At this point, the function returns 1 (since the factorial of 0 is 1 by definition), which ends the recursion.

Here is how the solution will look:

C#
1using System; 2 3public class Solution 4{ 5 public int Factorial(int n) 6 { 7 // Base case: factorial of 0 is 1 8 if (n == 0) 9 { 10 return 1; 11 } 12 // Recursive case: multiply n by factorial of n-1 13 else 14 { 15 return n * Factorial(n - 1); 16 } 17 } 18 19 public static void Main(string[] args) 20 { 21 Solution solution = new Solution(); 22 // Example usage 23 Console.WriteLine(solution.Factorial(5)); // Outputs 120 24 } 25}
Next: Practice!

Understanding recursion is crucial, as it's applied in many areas of computer science, like algorithms, data structures, etc. This lesson was just a warm-up. Now, it's time for practice to solidify your understanding and further build upon this knowledge. Remember, practice is the key!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.