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.

Java Programming Language (Article) (Program)

17

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:

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

Output:


                                        

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.


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.