Help understand modular operation in a circular array

I have a little problem trying to figure out how a modular operation is calculated. I create a queue, so I have a circular array. I cannot understand how this modular operation works.

Given q: a character array with a length of 5 elements, the MAX constant gives the maximum length of the array "5", rare is int, which represents the first available spot in the q array

    public void enqueue(Character c)throws FullQueueException{

    if(size()== MAX -1){ //if only 1 place left, is full, throw exc 

        throw new FullQueueException("Queue is full");
    }
    q[rare]=c;  
    rare=(rare+1)%MAX;
}

Now, assuming that the rare “first blank spot” is three, what will be the rare value after the method finishes? this is what I don’t get, rarely = (rare + 1)% MAX means rare = 4% 5, which gives rarity = 0.8.

Same for method size:

public int size() {

    return (MAX - front + rear) % MAX;
}

, int, , 1 4, 3 , (5-1 + 4)% 5, 8% 5, 1,6, 3 ? , java, , , . !

+3
2

, , modulo. . , .

4% 5 = 4 ( 4/5 0, 4)

8% 5 = 3 ( 8/5 1 3)

, , modulo, , . .. (, 7, MAX 8, , , , 8% 8 0).

+4

. modulo , .

a % b is the same as (a - a / b * b) 

, . (, b )

int result = a;
while(a >= b) a -= b;
while(a + b <= 0) a += b;

rare = (rare + 1) % MAX , .

rare = (rare == MAX - 1 ? 0 : rare + 1);
0

All Articles