# Thread: checking array items are equal

1. Member
Join Date
Feb 2011
Posts
53
Rep Power
0

## checking array items are equal

Hey iv been working on a problem, but cannot seem to solve it. I want to check if an item in an array is equal to the item infront. I have researched a lot and came up with the following which doesent work the way i expected :

The problem i am having is that say if i have an array of [1,2,1,2,1,2,1,2,1,2] this should mean i cycle through the array adding one to the total only if it comes directly after another number the same eg. [2,2,2,2] should bring the total variable to 4 but [1,2,1,2] should leave total at 0. But it does not. Also note, i have added the elements to the array, i just cut that part out as it works correctly.

Any help in solving this would be good :)
Last edited by trishtren; 10-19-2011 at 07:46 PM.

2. Senior Member
Join Date
Nov 2010
Posts
210
Rep Power
7

## Re: checking array items are equal

Wouldn't [2,2,2,2] result in 3, since you only start comparing numbers at the second element?

Here's some structured English (I hope I understood the specification properly):

Code:
```for each element of totals[] except the first
if this element is equal to the previous element
end if
end for```

3. Member
Join Date
Feb 2011
Posts
53
Rep Power
0

## Re: checking array items are equal

hmm this seems along the right lines, only i really wanted to start at the first element. and i also want to compare it to the item in front not the previous element. The main problem is that it adds to the count regardless. So even if there is a gap like [1,2,1,2] then it still seems to be saying their are two 1's next to each other.

4. Senior Member
Join Date
Nov 2010
Posts
210
Rep Power
7

## Re: checking array items are equal

One problem is that youre incrementing your loop counter in the if statement. Instead of totals[i++], use totals[i+1]. In fact, (totals[i] == totals[i++]) will always be true, since i++ evaluates to the current value of i before incrementing it.

This won't solve it entirely, but it will mean that your loop runs from start to finish without skipping anything.

Doesn't matter whether you start at 0 and stop at the penultimate one, or start at 1 and stop at the last one - either way, every element gets checked except one at the end where there's nothing to compare it to.
Last edited by Iron Lion; 10-16-2011 at 12:17 PM.

5. Member
Join Date
Feb 2011
Posts
53
Rep Power
0

## Re: checking array items are equal

hmm this seems to be working very nicely. Thanks for your time, i actually learned something quite valuable about the ++ operator!

6. Senior Member
Join Date
Nov 2010
Posts
210
Rep Power
7

## Re: checking array items are equal

No problem. Here's some more info on it. In particular, note the difference between i++ and ++i.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•