Recursion

This lesson introduces the concept of recursion and how it is implemented in C#

We'll cover the following...

Introduction

Recursion can be defined as:

A method that calls itself until a specific condition is met.

Example

An excellent and simple example of recursion is a method that will get the factorial of a given number:

Press + to interact
using System;
class FactorialExample
{
static void Main()
{
Console.WriteLine("Factorial of 4 is: {0}",Factorial(4));
}
public static int Factorial(int number)
{
if(number == 1 || number == 0) // if number equals 1 or 0 we return 1
{
return 1;
}
else
{
return number*Factorial(number-1); //recursively calling the function if n is other then 1 or 0
}
}
}

Code Explanation

In the ...