# Why not just make a condition instead of other loops?

int * mergeArrays(int arr1[], int arr2[], int arr1Size,int arr2Size)

{

``````int * arr3; // creating new array

arr3 = new int [arr1Size+arr2Size];

int lastIndex1 { }, lastIndex2 { };

for(int i = 0; i < arr1Size+arr2Size; i++) {

if(arr1[lastIndex1] <= arr2[lastIndex2] && lastIndex1 < arr1Size ) {

arr3[i] = arr1[lastIndex1++];

}

else {

if( lastIndex2 < arr2Size)

arr3[i] = arr2[lastIndex2++];

}

}

return arr3; // returning array
``````

}

@AHMED_IBRAHIM_HASSAN Your indices go out of bounds on this condition
arr1[lastIndex1] <= arr2[lastIndex2]
You must check that they are in bounds before you access them.
if( lastIndex1 < arr1Size && arr1[lastIndex1] <= arr2[lastIndex2])

But this condition is not enough, you are still going out of bounds on the check for arr2[lastIndex2]
To fix this problem you must ask yourself what is a default condition that you would want to pick arr1, and that is when lastIndex2 is already out of bounds. By skipping the rest of condition with an “or” you avoid the out of bounds problem.
if(lastIndex2 >= arr2Size || (lastIndex1 < arr1Size && arr1[lastIndex1] <= arr2[lastIndex2]))

You can remove the last if check, if( lastIndex2 < arr2Size) it is unnecessary.
In my opinion the solution that was provided has easier conditions and is in general, easier to understand which is why I think they chose the solution they did.