Problem
I am going trought the array and counting all the elements which are the same. The answer given above is correct, 1 one occurs twice an 3 occurs 4 times. Why I am getting an out of bounds error?

I could not find your logic correct. But I can say the reason for the exception. In the first for loop you are incrementing i value twice per iteration. So in the 3rd iteration i value will be 4. But when you say a[i++]=x; it will be a[4]=x; But the array a can have only 4 elements upto a[3]. That is the problem.