Circular Arrays

PAUL DAVIES
2 min readFeb 6, 2021

Hello friends, long time and am back.

Let us do a very short yet precise intro as you welcome me back. That is on circular arrays.

First, what is a circular arrays by the way? Oh, even before that, what is an array?

An array is a data structure that stores items contiguously in memory and the items can be accessed using their indexes. Because the items items are accessed using indexes the operation runs in O(1).

Example of arrays in java: int[] numbers = {10, 41, 30, 55, 10}.

The index of item 10 is 0, that of 41 is 1 and so forth. Actually the arrays start being stored at index 0, 1, 2 etc.

Wow, that was a brief and am sure even if you do not have programming background you now know what an array in programming is and looks like.

Now, arrays are categorized into major two. Linear and Circular arrays.

Linear array has a fixed length and when it is full you cannot add more items.

That then defines what circular arrays are. They virtually form a circle. In the sense that when its length is reached, the next item is stored from the starting point (index 0). Thereby the name, circular.

But how is the index determined then?

Two parts are taken into consideration:

Before the length is reached and after it is surpassed.

Before the length: index = size;

After the length: index = (size +1) % capacity.

where size is the number of items currently in the array and capacity is the length of the arrays.

Sorry if that is confusing but let me give you an example. Consider and array of length 5. items will be stored from index 0 all the way to 4 e.g [10, 20, 30, 40, 50]. But what if we added three more items says 60, 70 and 80?

10 -> 0 (size is 0 initially so index = size)

20 -> 1 (Size is 1 now and the index is 1)

30 -> 2

40 -> 3

50 -> 4

60 -> 0 (index = size % capacity => 5 % 5 = 0=> The reminder is 0 and that is the next index)

70 -> 1 (index = size % capacity => 6 % 5 = 1=> The reminder is 1 and that is the next index)

80 -> 2

As a result, by the time we are storing 70, our array will look like [60, 70, 30, 40, 50] where 30 is the first item and 70 the last.

Pick the below code java and run it. It will show you the wonders of circular arrays. You can modify it and play with it.

import java.util.Arrays;

public class Main {
public static void main(String[] args) {
int[] numbers = new int[5];
int counter = 0;
int value = 10;
while(counter < 7) {
int index;
if (counter < numbers.length)
index = counter;
else
index = counter % numbers.length;

numbers[index] = value;
value += 10;
counter++;
}

System.out.println(Arrays.toString(numbers));
}

}

Thank you friends. At least give me a clap!!

--

--

PAUL DAVIES

Software Developer; Java, Angular2+,RxJS,Spring boot,Android