Search code examples
c#loopsrecursionnested

How to write recursive function for nested loops in C#


How can I write recursive function for this for loops I am making sum of this array elements.

        int[,,,] exampleArray = new int[1,2,3,4];
        int sum = 0;
        for (int i = 0; i < 1; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                for (int k = 0; k < 3; k++)
                {
                    for (int l = 0; l < 4; l++)
                    {
                        sum += exampleArray[i, j, k, l];
                    }
                }
            }
        }
        Console.WriteLine(sum);

Solution

  • it is actually quite simple, just need a way to represent all 4 indexes as single variable:

    static int recursiveSum(int[,,,] a, int index = 0)
    {
        int ti = index;
        int l = ti % a.GetLength(3); ti /= a.GetLength(3);
        int k = ti % a.GetLength(2); ti /= a.GetLength(2);
        int j = ti % a.GetLength(1); ti /= a.GetLength(1);
        int i = ti % a.GetLength(0); ti /= a.GetLength(0);
    
        if (ti > 0) {
            return 0;
        }
    
        return a[i, j, k, l] + recursiveSum(a, index + 1);
    }
    
    static void Main(string[] args)
    {
        int[,,,] exampleArray = new int[1, 2, 3, 4];
        int sum = recursiveSum(exampleArray);
        Console.WriteLine(sum);
    }