The blog provides the technical approach on ” How to merge two one dimensional arrays in java ?”
Problem Statement:
How to merge two one dimensional arrays in java ?
Solution Approach:
- Get Count for 1st One dimensional array
- Get Array elements for 1st One dimensional array
- Get Count for 2nd One dimensional array
- Get Array elements for 2nd One dimensional array
- Iterate the 1st One dimensional array and add elements in the Result One Dimensional array
- Iterate the 2nd One dimensional array and add elements in the Result One Dimensional array
- Print the Result One Dimensional array
package com.java.planforexams.array;
import java.util.Scanner;
public class MergeDimensionalArrays {
public static void main(String[] args) {
int Array1Count = 0, Array2Count, TotalCount, i, j, k;
Scanner scan = new Scanner(System.in);
// enter size and elements of first array.
System.out.print("Enter size of the first array : ");
Array1Count = scan.nextInt();
int OneDimensionalInputArray_1[] = new int[Array1Count];
System.out.println("Enter elements of the first array : ");
for(i=0; i<Array1Count; i++)
{
OneDimensionalInputArray_1[i] = scan.nextInt();
}
// enter size and elements of second array.
System.out.print("Enter size of the second array : ");
Array2Count = scan.nextInt();
int OneDimensionalInputArray_2[] = new int[Array2Count];
System.out.println("Enter elements of the second array : ");
for(i=0; i<Array2Count; i++)
{
OneDimensionalInputArray_2[i] = scan.nextInt();
}
TotalCount = Array1Count + Array2Count;
int OneDimensionalMergeArray[] = new int[TotalCount];
// Iterate to merge the 1st Array Elements
System.out.print("Merging both the Arrays...\n");
for(i=0; i<Array1Count; i++)
{
OneDimensionalMergeArray[i] = OneDimensionalInputArray_1[i];
}
for(i=0, k=Array1Count; k<TotalCount && i< Array2Count; i++, k++)
{
OneDimensionalMergeArray[k] = OneDimensionalInputArray_2[i];
}
// Print the merged values
System.out.print(" ::::Merged Array values :::: :\n");
for(int incr=0; incr<TotalCount; incr++)
{
System.out.print(OneDimensionalMergeArray[incr] + " ");
}
}
}
Output:
Enter size of the first array : 3
Enter elements of the first array :
2
43
56
Enter size of the second array : 3
Enter elements of the second array :
54
67
88
Merging both the Arrays...
::::Merged Array values :::: :
2 43 56 54 67 88