I want to split array in two parts but I am unable to assign value in 2nd array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I want to split array in two parts but I am unable to assign value in 2nd array

https://code.sololearn.com/c1ktr5CBj2d9/?ref=app

25th Apr 2021, 10:40 AM
Harsh Pratap Singh
Harsh Pratap Singh - avatar
7 Answers
0
for(i = 0; i<newSize; i++){ for(int l = newSize; l<size; l++){ arr2[i] = arr[l]; } } That's the problem, you are assigning the same value to all of the elements in arr2, every element of arr2 is equal to the last element of arr
25th Apr 2021, 10:48 AM
Michal Doruch
0
How I am incrementing l
25th Apr 2021, 10:50 AM
Harsh Pratap Singh
Harsh Pratap Singh - avatar
0
Oh sorry i got it you are right
25th Apr 2021, 10:52 AM
Harsh Pratap Singh
Harsh Pratap Singh - avatar
0
Yes, you do, but imagine that, you overwrite the same element "arr2[i]" with all elements from arr[newSize] to arr[size-1] So you end up with the same value for each element (which is arr[size-1])
25th Apr 2021, 10:53 AM
Michal Doruch
0
Pls give some suggestion that how I can solve this problem
25th Apr 2021, 10:54 AM
Harsh Pratap Singh
Harsh Pratap Singh - avatar
0
i=0; for(int l = newSize; l<size; l++){ arr2[i++] = arr[l]; } You can add some protection, for example "if": i=0; for(int l = newSize; l<size; l++){ if(i<newSize) arr2[i++] = arr[l]; } It should work Anyway, your code works with even numbers only, for odd sizes it will work differently
25th Apr 2021, 10:58 AM
Michal Doruch
0
Question is for only even element only
25th Apr 2021, 11:15 AM
Harsh Pratap Singh
Harsh Pratap Singh - avatar