How to find the index of the next and previous element of a circular array

“low angle photography of white concrete building” by Carl Newton on Unsplash

If you have an array that is circular, i.e. the next element of the last element is the first element.

To find the next and the previous index we are going to rely of the modulus operator.

if curr is not the last element then (curr + 1) % N == curr + 1, hence the next index, however if (curr + 1) == N, i.e. the current element is the last index, then (curr + 1) % N == 0, therefore the next element will be the first element of the array.

if current is not the first element of the array, then (curr + N — 1) % N == (curr — 1) % N + N % N == curr — 1

However if curr == 0 , i.e. it is the first element, then (curr + N — 1) % N == (N — 1) % N == N — 1 , i.e. the index of the last element of the array.

This article demonstrated how we can craftily use the modulus operator to cover the corner cases while finding the next and previous element in a circular array. For more code walk through and coding tips, check out my other content. Happy coding !!!

--

--

Re-learning the fundamentals of programming.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store