Home / Programs / 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.
Programming Example

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.

👁 118 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

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, 6
  • Q[]: 7, 1, 8, 2

Output:

  • R[]: 4, 19, 4, 6, 23, 6, 7, 1, 8, 2

Program Code

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();
    }
}

Explanation

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.

How to learn from this program

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.