Skip to content
Advertisement

Merge two arrays in alternate fashion

I am trying to merge to arrays of int type with the same size. Here’s my code

JavaScript

When I try printing the numbers in first for loop, it gives me 1,4,2,5,3,6 which the correct output. But, When I try printing it outside the first for loop it gives me output 1,2,3,6,0,0. Can someone help me? TIA

Advertisement

Answer

In your for loop, when you copy from arr2 you need to increment your count.

JavaScript

You could also simplify your code a bit like,

JavaScript

And print in main like

JavaScript

or in Java 8+, use a flatMap and IntStream like

JavaScript

for the same result.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement