c++ - Shifting array elements by n positions -
i have basic knowledge in c, c++ , im trying insert n elements @ k positions in array , shift k+1 element in array. have used 2 loops this
void insert(int n,int k) { int temp=arraya[k][4]; for(int u=k+1;u<=rowa;u++) { arraya[k+n][4]=arraya[k+1][4]; arraya[k+n][3]=bigradius; arraya[k+n][2]=arraya[k+1][2]; arraya[k+n][1]=arraya[k+1][1]; arraya[k+n][0]=arraya[k+1][0]; } for(int pos=k;pos<=k+n-1;pos++,) { arraya[pos][4]=temp; arraya[pos][3]=b arraya[pos][2]=s1; arraya[pos][1]=s2; arraya[pos][0]=s3; } }
where n no of new elements,k position new elements inserted,s1,s2,s3..are values
if initial file 0.74172455 0.03613250 0.82822931 0.03121938 0 0.45620244 0.33476580 0.92169053 0.03121938 1 0.13701758 0.74540644 0.56569663 0.03121938 2 0.94162524 0.13094005 0.62107182 0.03121938 3
but in output if im inserting 3 elements in position 0,then elements @ position 1,2 missing
-0.0104065 0.0312194 0.0728452 0.0104065 0 0.0104065 -0.0312194 0.0520323 0.0104065 0 0.0104065 -0.0312194 0.0520323 0.0312194 0 0.941625 0.13094 0.621072 0.0312194 3
to insert n
elements @ index k
of array, try logic:
initialize original array having elements. now, take values of n
, k
in variables , n elements insert in array (let's to_add[]) user. now, initialize second array of length = length of main array + n.
(1) having required values , arrays initialized, run loop index = 0
index = k-1
of main array , copy elements the second array.
(2) now, run second loop index = k
index = k + n - 1
second array , copy elements index = index - k
of to_add array second array.
(3) lastly, run third loop index = k + n
index = (length of second array) - 1
of second array , copy elements index = index - n
of main array second array.
here's c++ code above logic.
int k,n; int main_array[x] = { /* elements of original array */ }; /* display main array */ cout << "enter index position @ enter elements \n" ; cin >> k; cout << "\n how many elements want enter? \n" ; cin >> n; int to_add[n]; int final_array[x+n]; /* accept elements added to_add array */ //first loop for(int = 0; < k; i++){ final_array[i] = main_array[i]; } //second loop for(int = k; < k+n; i++){ final_array[i] = to_add[i-k]; } //last loop for(int = k+n; < x+n; i++){ final_array[i] = main_array[i-n]; } /* display final_array */
i hope understand , solves problem.
Comments
Post a Comment