Sukwoo Sukwoo - 1 month ago 14
C Question

shift elements in array

This is elementary, but my googling just doesn't cut it. I know I have to do something else to shift the values of an array one by one, but the below coding gives me the same values for items[k] to items[infinity] all equaling items[k]. What I don't understand is how to preserve the original k+1 value while I copy the k value into the k+1 slot.

if ( i < numItems) //if i is inside the used boundaries of the array
{
for (int k = i; k < numItems; k++) //shift the array values from point i
{
double temp = 0.0;
temp = items[k];
items[k+1] = temp;
}

items[i] = value; //and insert value into i
}


Does it has to be a recursive method?

Answer

An easy option would be to iterate through the array in reverse

for (int k = numItems; k > i; k--){   
    items[k]=items[k-1];
}

Option 2:

If you want to keep your method intact then you can also use the temp variable differently

before your for loop initialize temp to

double temp = items[i];

and then in the loop you can use temp to store the [k+1] value in temp rather than storing the [k] value.

items [k+1] = temp;
temp = items [k+1];
items[k+1] = items[k];

also you should watch your boundaries so that k+1 is not going past the last element in the array. You could use something like numItems - 1 with a check before, to ensure that the array is not empty.