shift positions inside of an array?
#1

let's say i have an array of 5 integers like this:

pos 0: 100
pos 1: 200
pos 2: 300
pos 3: 400
pos 4: 500

now i need to insert another integer with value 50 at "pos 0" but i want all of the values to remain except the last one, so the array will look like this:

pos 0: 50
pos 1: 100
pos 2: 200
pos 3: 300
pos 4: 400

so basically everything should shift the position by 1 to make space for the new value

is there some technique to do this fast and easy?!
Reply
#2

A simple loop.

Код:
for(new i = sizeof(array) - 1; i > 0; i --)
{
array[i] = array[i - 1];
}

array[0] = new_value;
Assuming an array size of 5, it first moves index 3 to 4, then 2 to 3, then 1 to 2 and last 0 to 1.
After that overwrite index 0 with the new value.
Reply
#3

thank you NaS
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)