Can't understand why ArrayOutOfBoundsException is thrown

Hello,

My question is with reference to the following code

https://www.codechef.com/viewsolution/42598947

If I do it in the following way, I get an ArrayIndexOutOfBounds Exception

for(int k=0;k<n;k++){
    if(a[k+1]<=a[k]) 
        cnt++;
    else
    	a[k+1]=a[k]; 
    }

Can someone please explain why this is so?
I’m new to this platform, any help or suggestions are appreciated!!

Thanks!

I see that k loop is upto n-1.

if you do k+1, it will become n and since the size of an array is 0 to n-1, it will throw that exception.

1 Like

Ohh yes, missed that!! Thanks a lot!