Home

C# Example: Recursion

 

Introduction

This is an example of recursion: a function that calls itself:

using System;

public class Program
{
    static int Additional(int a)
    {
        if( a <= 1 )
            return 1;
        return a + Additional(a - 2);
    }
    
    static int Main()
    {
        Console.WriteLine("Additional: {0}\n", Additional(5));
        Console.WriteLine("Additional: {0}\n", Additional(11));
        Console.WriteLine("Additional: {0}\n", Additional(28));
        Console.WriteLine("Additional: {0}\n", Additional(55));
        return 0;
    }
}

This would produce:

Additional: 9

Additional: 36

Additional: 211

Additional: 784

Press any key to continue . . .

 

 

 

Home Copyright © 2007-2013, FunctionX