Write a program to create 2 single dimension arrays in order to store 10 numbers respectively, then merge the values of both the arrays into third array so that the values of first array and second array will be alternate to each other, then display values of the merged array.
Alternate means third array will carry values of first and second arrays as follows:
c[0]=a[0]
c[1]=b[0]
c[2]=a[1]
c[3]=b[1]
c[4]=a[2]
c[5]=b[2]
c[6]=a[3]
c[7]=b[3]
..... where above digits are the index position not the values
Use java.util.* package and for loop.
public class Main {
public static void main(String[] args) {
int[] a = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int[] b = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int[] c = new int[a.length + b.length];
for (int i = 0, j = 0, k = 0; i < c.length; i++) {
c[i] = i % 2 == 0 ? a[j++] : b[k++];
System.out.print(c[i] + " ");
}
System.out.println();
}
}
Comments
Leave a comment