1. ## array shift problem

Hi, I have written a small piece of code that runs through a loop of 100 array elements. It compares a variable (conttot) to each of these elements and tests to see if it is larger. If the variable is larger it shifts the other elements down the array by 1 place to make room for the new element. The new element is then inserted in the correct place (above the smaller values in the array)

I have been trying to debug this for a while, but with no success.
The output i am getting is the biggest value in the first slot, and the second largest element duplicated all the way down to the 100th.

can anybody see where the problem may be?

bob

Code:
```    //tests each element starting with biggest.
for(a=0;a<=100;a++)
{
if(conttot>=colourArr[a])
{
//shift all the other elements down to make room for the newest..
for(d=100;d>a;d--)
{
colourArr[d]=colourArr[d];
purecolours[d][0]=purecolours[d-1][0];
purecolours[d][1]=purecolours[d-1][1];
purecolours[d][2]=purecolours[d-1][2];
}

//place the new element in its correct slot
colourArr[a]=conttot;
purecolours[a][0]=red;
purecolours[a][1]=green;
purecolours[a][2]=blue;
break;
}
}```

2. can anybody see where the problem may be?
You misspelled color? Oh, wait...

I'm not exactly sure what you're trying to do. Are you trying to sort the array, or just insert new values at the correct place? If you're inserting new values into an already full array, which value gets bumped?
Code:
```for(a=0;a<=100;a++)
{
if(conttot>=colourArr[a])```
In the array colourArr[100] the array elements are numbered 0-99. In your for statement, the last value of 'a' will be 100, which is past the end of array. Your for statement should be
Code:
`for(a=0;a<100;a++)`
Same problem here...
Code:
`for(d=100;d>a;d--)`
...'d' should start out at 99 instead of 100. Also,
Code:
`colourArr[d]=colourArr[d];`
doesn't make sense. You're setting colourArr[d] equal to itself.

fletch

3. Hi, thx for your reply. Thx for pointing out the <=100 etc. stuff.
colourArr[d]=colourArr[d]; was a typo..

I solved the problem myself as i was writing a response

if(conttot>=colourArr[a])
was originally set to >= to replace a value if it aready existed (was equal to). there are lots of duplicate values of contot.

by inserting:
Code:
```    for(d=100;d>a;d--)
{
colourArr[d]=colourArr[d];
purecolours[d][0]=purecolours[d-1][0];
purecolours[d][1]=purecolours[d-1][1];
purecolours[d][2]=purecolours[d-1][2];
}```
and shifting the elements i effectively removed the replacement that should have occurred. Sticking another if in solved my problems..

thanks anyway

bob

4. Originally posted by fletch
You misspelled color? Oh, wait...
It's the british spelling and it was the standard
(and it is) for many years in many countries
except USA and its neighbours.

(also... neighbors )