Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relooping through array

Tags:

java

arrays

So let's say I have an array of length 5 (let's just call it myArray[5]). If I add 4 to myArray[3], such like myArray[3+4], how can I make it loop through myArray again so that it becomes myArray[2]?

example)

myArray[3]

myArray[4]   //+1

myArray[0]   //+2

myArray[1]   //+3

myArray[2]   //+4
like image 975
Ricky Su Avatar asked May 14 '26 22:05

Ricky Su


2 Answers

Just use the array length for a modulo operation:

int index = /* index you are using */;
myArray[index % myArray.length]
like image 185
Rogue Avatar answered May 17 '26 11:05

Rogue


You can use modulus. index % myArray.length like

int[] myArray = new int[10];
for (int i = 10; i < 20; i++) {
    System.out.println(i % myArray.length);
}

Output is 0 - 9 (inclusive).

like image 33
Elliott Frisch Avatar answered May 17 '26 12:05

Elliott Frisch