Write a program to store 6 elements in an array P and 4 elements in an array Q, and produce a third array R containing all the elements of arrays P and Q. Display the resultant array.
Example:
Input:
P[]: 4, 19, 4, 6, 23, 6Q[]: 7, 1, 8, 2Output:
R[]: 4, 19, 4, 6, 23, 6, 7, 1, 8, 2import java.io.*;
class Merge {
int P[] = new int[6];
int Q[] = new int[4];
int R[] = new int[10];
int i, j;
void display() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Input elements for array P
System.out.println("Enter 6 elements for array P:");
for (i = 0; i < 6; i++) {
P[i] = Integer.parseInt(br.readLine());
}
// Input elements for array Q
System.out.println("Enter 4 elements for array Q:");
for (i = 0; i < 4; i++) {
Q[i] = Integer.parseInt(br.readLine());
}
// Merge arrays P and Q into R
for (i = 0; i < 6; i++) {
R[i] = P[i];
}
for (i = 6, j = 0; j < 4; j++, i++) {
R[i] = Q[j];
}
// Display the resultant array R
System.out.println("Resultant array R:");
for (i = 0; i < 10; i++) {
System.out.print(R[i] + " ");
}
}
public static void main(String[] args) throws IOException {
Merge merge = new Merge();
merge.display();
}
}
Variable Table
| Variable | Type | Description |
|---|---|---|
P[] |
int[] |
To store 6 integer values. |
Q[] |
int[] |
To store 4 integer values. |
R[] |
int[] |
To store the merged result of P and Q. |
i |
int |
Loop variable for iterating through arrays. |
j |
int |
Loop variable for iterating through Q. |
This code merges two arrays, P and Q, into a third array R and displays the resultant array.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.