Q:

Java program to merge two one dimensional arrays

belongs to collection: Java Array Programs

0

Given two one-dimensional arrays and we have to merge them using java program.

Example:

Input:
Array 1 (elements will be read in program): 1 2 3 4 5 6 7 8 9 10
Array 2 (elements will be read in program): 11 12 13 14 15
Output:
New array (After merging elements)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to merge two one-dimensional array elements in java

import java.util.Scanner;

public class ExArrayMerge {
  public static void main(String args[]) {
    // initialize the required array.
    int size1, size2, size, i, j, k;
    int arr1[] = new int[50];
    int arr2[] = new int[50];
    int merge[] = new int[100];
    Scanner scan = new Scanner(System.in);

    // enter size and elements of first array.
    System.out.print("Enter size of the first array : ");
    size1 = scan.nextInt();

    System.out.println("Enter elements of the first array : ");
    for (i = 0; i < size1; i++) {
      arr1[i] = scan.nextInt();
    }

    // enter size and elements of second array.
    System.out.print("Enter size of the second array : ");
    size2 = scan.nextInt();

    System.out.println("Enter elements of the second array : ");
    for (i = 0; i < size2; i++) {
      arr2[i] = scan.nextInt();
    }

    // merge both the array.
    System.out.print("Merging both the Arrays...\n");
    for (i = 0; i < size1; i++) {
      merge[i] = arr1[i];
    }

    size = size1 + size2;

    for (i = 0, k = size1; k < size && i < size2; i++, k++) {
      merge[k] = arr2[i];
    }

    // new array after merging.
    System.out.print("New array after merging is :\n");
    for (i = 0; i < size; i++) {
      System.out.print(merge[i] + "  ");
    }
  }
}

Output

Enter size of the first array : 10
Enter elements of the first array : 
1
2
3
4
5
6
7
8
9
10
Enter size of the second array : 5
Enter elements of the second array : 
11
12
13
14
15
Merging both the Arrays...
New array after merging is :
1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to sort a one dimensional array in as... >>
<< Java program to print EVEN and ODD elements from a...