Write a program to merge two arrays elements to store third array


This is a Java program that takes two arrays as input and merges them into a third array. The user is prompted to enter the size of the two arrays, as well as the elements of each array. The program then creates a third array of size 100 (which is more than enough to hold the merged array) and populates it with the elements of the first array, followed by the elements of the second array.

Here's a step-by-step explanation of the program:

  • The program starts by importing the Scanner class, which is used to read user input from the console.
  • The Third_Array class is defined.
  • The main method is defined. This is the entry point of the program.
  • An instance of the Scanner class is created to read user input.
  • The user is prompted to enter the size of the first array, which is stored in the variable n.
  • The user is prompted to enter the size of the second array, which is stored in the variable m.
  • Two arrays a and b are created with sizes n and m, respectively.
  • An array c of size 100 is created to hold the merged array.
  • The user is prompted to enter the elements of the first array a, which are stored in the array.
  • The user is prompted to enter the elements of the second array b, which are stored in the array.
  • A loop is used to copy the elements of the first array a to the third array c, starting at index 0.
  • Another loop is used to copy the elements of the second array b to the third array c, starting at index k (which is the index after the last element of the first array).
  • The merged array c is printed to the console.
  • The program ends.

Source Code

import java.util.Scanner;
class Third_Array
{
	public static void main(String[] args)
	{   
		Scanner input =new Scanner(System.in);
		System.out.print("Enter the First Array Limit :");
		int n =input.nextInt();
		System.out.print("Enter the Second Array Limit :");
		int m =input.nextInt();
		int [] a =new int[n];
		int [] b =new int[m];
		int [] c =new int[100];
		int k=0;
		for(int i=0;i<n;i++)
		{
			System.out.printf("Element of a[%d] :",i);
			a[i]=input.nextInt();
		}
		for(int i=0;i<m;i++)
		{
			System.out.printf("Element of b[%d] :",i);
			b[i]=input.nextInt();
		}
		for(int i=0;i<n;i++)
		{
			c[k] = a[i];
			k++;
		}
		for(int i=0;i<m;i++)
		{
			c[k] = b[i];
			k++;
		}
		System.out.print("\nMerge two Array Elements ...\n");	
		for(int i=0;i<k;i++)
		{
			System.out.printf("\nc[%d] = %d",i,c[i]);
		}
    }
}
 

Output

Enter the First Array Limit :5
Enter the Second Array Limit :5
Element of a[0] :1
Element of a[1] :2
Element of a[2] :3
Element of a[3] :4
Element of a[4] :5
Element of b[0] :6
Element of b[1] :7
Element of b[2] :8
Element of b[3] :9
Element of b[4] :10

Merge two Array Elements ...

c[0] = 1
c[1] = 2
c[2] = 3
c[3] = 4
c[4] = 5
c[5] = 6
c[6] = 7
c[7] = 8
c[8] = 9
c[9] = 10

Example Programs