Skip to content

Instantly share code, notes, and snippets.

@ivanxpetrov
Created April 22, 2018 22:01
Show Gist options
  • Save ivanxpetrov/4667dad036e1d8c8ea143f46e20725b4 to your computer and use it in GitHub Desktop.
Save ivanxpetrov/4667dad036e1d8c8ea143f46e20725b4 to your computer and use it in GitHub Desktop.

Revisions

  1. Ivan Petrov created this gist Apr 22, 2018.
    34 changes: 34 additions & 0 deletions RecursiveSum.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    void Main()
    {
    var list0 = new List<int>();

    var list1 = new List<int>()
    {
    1
    };

    var list2 = new List<int>
    {
    0,1,-2
    };

    Sum(list0).Dump($"{list0.Stringify()}");
    Sum(list1).Dump($"{list1.Stringify()}");
    Sum(list2).Dump($"{list2.Stringify()}");
    }

    int Sum(IList<int> listNumbers, int startIndex = 0)
    {
    if (startIndex == listNumbers.Count)
    {
    return 0;
    }

    if (startIndex == listNumbers.Count - 1)
    {
    return listNumbers[startIndex];
    }

    return listNumbers[startIndex] + Sum(listNumbers, startIndex + 1);
    }