I have a question about adding say integers to an array-based list of numbers.
I know how to add something at the end it would be something like:
values[count] = newValue;
count ++;

What about if someone wanted to add something to the beginning or somewhere between? My book doesn't say how to do such things because with an unsorted list order doesn't matter so it only thinks you would just throw things on the end. But what if you didn't want to?

>What about if someone wanted to add something to the beginning or somewhere between?
It's more or less the same deal. You move everything from the index you want to add to, to the end of the array forward by one element. Then you add the new value to the index you want and increase the count:

for ( int i = count; i > index; i-- )
  values[i] = values[i - 1];

values[index] = newValue;
++count;

It's not desirable because it's potentially very expensive to shift array elements like that.

If you want to keep all existing values in the array then you need use a loop to shift everything down from the spot you want to add the new value.

[edit]^^^ what Narue said [/edit]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.