18

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?

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
Sukwoo
  • 205
  • 2
  • 5
  • 9

4 Answers4

39

You can as well use memmove, that handles overlap of regions.

memmove(&items[k+1], &items[k], (numItems-k-1)*sizeof(double));
items[k] = value;
Teudimundo
  • 2,610
  • 20
  • 28
10

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.

Ryan1729
  • 940
  • 7
  • 25
Jasmeet Oberai
  • 116
  • 1
  • 2
0

Can you try reversal method

this is an example.

// reverse array from start to end
void reverse(int a[], int start, int end)
{
  int i;
  int temp;
  while(start++ < end--)
  {
    temp = a[start];
    a[start] = a[end];
    a[end] = temp;
  }
}

// function that will rotate array by d elements
void rotateArray(int a[], int d, int n)
{
  reverse(a, 0, d-1);
  reverse(a, d, n-1);
  reverse(a, 0, n-1);
}
vsmph
  • 108
  • 1
  • 11
-2
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    int i,j=0,s;
    int n,k;
    int A[n];

    scanf("%d %d",&n,&k);
    if(((n>=0) && (n<=100000))&&(k>=0)){
        for(i=0;i<n;i++){
            scanf(" %d", &A[i]);
        }
        if(k>=n){
            k=k-n;
        }else{
        for(j=0;j<n;j++){
            s=j+k;
            if(s>n){
                s-=n;
                A[j]=A[s];
            }else{
            A[j]=A[s];
            }

        }
        for(i=0;i<n;i++){
            printf("%d ",A[i]);
        }
      }
    }
    return 0;
}