Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading