Out of range index problem

I have the following two loops for sequence. It is very strange that the first for loop works when I run it alone. But when I run the second loop alone, I get an exception error out of range. Can someone help me check what the error is? Thank you very much!

for (i = NiPricePointer; i < 551; i++) { tempUpper = tempUpper + NiPriceCounter[i]; if (tempUpper >= (NiPriceRounds * 0.3)) { chart3.Series["Upper 30%"].Points.AddXY(k * 500, ((i - 1) * 0.1 + 5)); break; } } for (i = NiPricePointer; i>0; i--) //This loop always gives me out of range problems. { tempLower = tempLower + NiPriceCounter[i]; if (tempLower >= (NiPriceRounds * 0.3)) { chart3.Series["Lower 30%"].Points.AddXY(k * 500, ((i - 1) * 0.1 + 5)); break; } } 

Array initialization:

 int[] NiPriceCounter = new int[551]; 

Thanks a lot!

+4
source share
4 answers

I believe that NiPricePointer is just over 550. Both of your loops should contain both borders as a check:

 for (i = NiPricePointer; i < 551 && i >=0; i++) 

and

 for (i = NiPricePointer; i < 551 && i >=0 ; i--) 
+5
source

after the first cycle, the NiPricePointer growth will increase by 1 so your second cycle should be
for(i = NiPricePointer-1;i>0;i--);

0
source

Add this to every loop.

 Debug.Assert((i < 551) && (i >= 0)); 
0
source

Change it

for (i = NiPricePointer; i> 0; i -)

Wherein:

for (i = 550; i> = 0; i -)

0
source

Source: https://habr.com/ru/post/1341834/


All Articles