# checking array items are equal

Printable View

• 10-16-2011, 11:59 AM
trishtren
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 :)
• 10-16-2011, 12:07 PM
Iron Lion
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         add 1 to count     end if end for```
• 10-16-2011, 12:12 PM
trishtren
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.
• 10-16-2011, 12:13 PM
Iron Lion
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.
• 10-16-2011, 12:20 PM
trishtren
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!
• 10-16-2011, 12:23 PM
Iron Lion
Re: checking array items are equal
No problem. Here's some more info on it. In particular, note the difference between i++ and ++i.