3

I am looking to create a program like the following (c# btw):

int[] arr = new int[9]
//some code that puts values 1, 0, or 2 in each array element
for(int i = 0; i < arr.Length; i++)
{
    if (arr[i] == arr[i + 3]) { return true; }
}

So, for each value in the array I am applying a formula that does something with that value and the value 3 indexes ahead of it. Of course, this runs into an out of range exception once i+3>8.

What I'd like to do is if the the desired index is out of range then loop the index values back around to the beginning of the array. So, in an array of length 9 where the last index is 8, if on a given loop i = 7, and i+3 then = 10, I would like i+3 to 'become,' by whatever means, 1, and then when i = 8, and i+3 = 11, I want i+3 to become 2.

So, the index pairs being evaluated would be something like:

i , i+3

0 3

1 4

2 5

3 6

4 7

5 8

6 0

7 1

8 2

how can I go about doing this?

Thanks for any help.

1
  • 1
    What have you tried doing? Have you already learned about the % operator? What is the problem? Commented Apr 9, 2017 at 16:34

2 Answers 2

4

Use the modulo operator like this:

if (arr[i] == arr[(i + 3) % arr.Length]) { return true; }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I was afraid that this would be difficult/impossible to implement!
3

You could try the following expression inside your if statement.

arr[i] == arr[(i + 3) % arr.Length];

The % Operator

Divides the value of one expression by the value of another, and returns the remainder.

2 Comments

@Johnbot My bad...Thanks, I corrected the link. However, regarding the name, I don't think is wrong we call it Modulus operator. You will find with a bit googling this term also be used as the term remainder operator.
This answer shows the difference between the two and is also applicable to C#.

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.