×

Java Programs

Java Practice

Java program to merge two one dimensional arrays

In this java program, we are going to learn how to merge two one dimensional arrays? By IncludeHelp Last updated : December 23, 2023

Problem statement

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

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  

Java Array Programs »

More Java Array Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.