Shift elements in an array

This is elementary, but my googling just doesn’t cut. I know that I need to do something else to offset the values ​​of the array one by one, but the encoding below gives me the same values ​​for the elements [k] for the elements [infinity] of all equal elements [k]. I don’t understand how to keep the original value of k + 1 when copying the value of k to slot k + 1.

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 } 

Should there be a recursive method?

+7
source share
4 answers

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, you can also use a temporary variable in different ways

before your for loop initializes temp so that

 double temp = items[i]; 

and then in a loop, you can use temp to store the value [k + 1] in temp instead of saving the value [k].

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

you should also keep track of your borders so that k + 1 does not pass by the last element of the array. You can use something like numItems-1 with validation before to make sure the array is not empty.

+5
source

You can also use memmove, which handles overlapping areas.

 memmove(&items[k+1], &items[k], (numItems-k-1)*sizeof(double)); items[k] = value; 
+17
source

Can you try the 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); } 
0
source
 #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=kn; }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; } 
0
source

All Articles