I build this code which displays all entries of an array in queue fashion. The problem is that I was told that this could be done without for statement which rewind content of i to 0, but I can’t figure out how.
How else this could be done?
public void display()
{
int i = frontIndex;
while(true)
{
if (i == numberOfItems)
i = 0;
System.out.print(array[i++] + " ");
if (i == rearIndex + 1)
break;
}
}
You can use the
%operator and print thei % numberOfItems:It is not tested, but it should be something along the lines of:
The idea is
(array.length + k) % array.length == k, so using the%operator, is actually equivalent to resetting the indexiback to 0.