How to avoid going out of range when checking next key in a for loop?


I have an array of 10 integers. What my for loop does is to check the value for (k-2), (k-1), k, (k+1) and (k+2) on every iteration.

But for the iteration where k=8, I would like to check (k - 3) instead of (k + 2) because it would throw an error otherwise
Same for k=9 , I want to check (k-4), (k-3), (k-2), (k-1) and k.

How can I achieve that?

Thanks in advance

Sounds fun, though what will k=0 and k=1 check?