0

I have to remake a recursive program to dynamic for university task and when doing this I bumped into an error: Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. The error seems to happen in line, where is max = Max(sum2[l], array[j - 1, i - 1]);

        static int F2(int k, int n)
        {
            int[] sum2 = new int[100];
            int max = 0;

            int[,] array = new int[n + 1, k + 1];
            for (int i = 0; i <= n; i++)
            {
                for (int j = 0; j <= k; j++)
                {
                    //array[i, j] = int.MaxValue;
                    if (i == 0) array[i, j] += 0;
                    else if (j == 1) array[i, j] += p[i];
                    else
                    {

                        for (int l = 1; l < n; l++)
                        {
                            for (int e = l; e < n; e++)
                                sum2[l] += p[i];

                            max = Max(sum2[l], array[j - 1, i - 1]);
                            array[i, j] = int.MaxValue;
                            if (max < array[i, j]) array[i, j] = max;

                        }

                    }
                }
            }
            return array[k, n];
        }
        public static int Max(int a, int b) { return a > b ? a : b; }

Recursive program code

So any toughts on how to fix this and what do I do wrong?

Ali G.
  • 13
  • 1
  • 6
  • 2
    What is your program supposed to do? What is the goal you're trying to achieve? If you want to access an array by index, they start on 0 (on a side note). in the most inner two for loops you're starting at 1 and using that value to access the array. i.e. an array of size 10 can be accessed with indexes 0-9. – Lennart May 16 '19 at 08:26
  • What are the values for k and n when you call the method, and the exception occurs? Have you tried putting a "try" around your code and catching the exception, followed by putting a breakpoint in the catch block? This way you would be able to inspect related values, like j and i. Also, why are you hard-coding the size of the sum2 array, while k and n affect the way it's being accessed? – Lennart May 16 '19 at 08:30
  • I had to remake this with code: [link](https://imgur.com/a/CeDZU0h) – Ali G. May 16 '19 at 08:30
  • What is `p[i]`? Is `n` always `< 101`? – Jimi May 16 '19 at 08:32
  • n=6 and k=2 and p[i] are always random numbers [link](https://imgur.com/a/PtBtXB8) – Ali G. May 16 '19 at 08:35
  • This is the whole code: [code](https://www.pastiebin.com/5cdd215d10f6b) – Ali G. May 16 '19 at 08:38

0 Answers0