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, 2
import 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 understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.