3

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

3 Answers 3

4

Just use the array length for a modulo operation:

int index = /* index you are using */;
myArray[index % myArray.length]
Sign up to request clarification or add additional context in comments.

Comments

2

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).

Comments

1

If you want to loop through the array in a circular fashion the modulus % operator is the way to go. If you combine that with the Java 8 streaming API:s the solution can look like this.

    int[] myArray = {1, 2, 3, 4, 5}; // Setup the array
    int startIndex = 3;              // Start index as per the OP's example
    int addIndex = 4;                // Add as per the OP's example

    // Loop via streams - no external looping
    IntStream.range(startIndex, startIndex + addIndex)
            .map(i -> myArray[i % myArray.length]) // circular loop
            .forEach(System.out::println /* Do your stuff */); // do your stuff

For more examples, see this answer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.