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

Why it is giving Index Out Of Range Exception if i don't pre calculate value?

i was trying to solve problem related to prefix sum.
In which array is given

var nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

and we have to find Sum of each elements in range a, b inclusive

function is giving System.IndexOutOfRangeException

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

I Tried to solve this ways.

int[] pre;
NumArray(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });

Console.WriteLine(SumRanges(0,2));
Console.WriteLine(SumRange(0,2));
void NumArray(int[] nums)
{
    pre = new int[nums.Length];
    pre[0] = nums[0];
    for (var i = 1; i < nums.Length; i++)
    {
        pre[i] += pre[i - 1] + nums[i];
    }
}
int SumRange(int left, int right)
{
    return pre[right] - left >= 1 ? pre[left - 1] : 0;
}
int SumRanges(int left, int right)
{
    int l = left >= 1 ? pre[left - 1] : 0;
    return pre[right] - l;
}

My Question is Why below function is giving System.IndexOutOfRangeException

int SumRange(int left, int right)
{
    return pre[right] - left >= 1 ? pre[left - 1] : 0;
}

but below equation won’t give System.IndexOutOfRangeException

int SumRanges(int left, int right)
{
    int l = left >= 1 ? pre[left - 1] : 0;
    return pre[right] - l;
}

i just only stored in variable, i am not getting why it is?

Please help me.

>Solution :

First, those two method’s logics are different I guess you think they are same

For this one

pre[right] - left >= 1 ? pre[left - 1] : 0;

the execution sequence is like this

(pre[right] - left >= 1) ? pre[left - 1] : 0;

It will compute the result of (pre[right] - left >= 1) first then execute others logic and you can change it to

return pre[right] - (left >= 1 ? pre[left - 1] : 0);

then they will be same

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