0

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?

3
Contributors
2
Replies
3
Views
10 Years
Discussion Span
Last Post by Ancient Dragon
0

>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.

0

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]

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.