Advertisement

How to search element of two combined array by index in Java?

 

How to search element of two combined array by index in Java?

How to search element of two combined array by index in Java?

import java.util.Scanner;
class HelloWorld {
    public static void main(String[] args) {
        int size1,size2;
        Scanner sc1=new Scanner(System.in);
        Scanner sc2=new Scanner(System.in);
        System.out.println("Enter the 1st array size:");
        size1=sc1.nextInt();
        System.out.println("Enter the 2nd array size:");
        size2=sc2.nextInt();
        int a[]=new int[size1];
        int b[]=new int[size2];
        int c[]=new int[size1+size2];
        System.out.println("Enter the values in 1st array:");
        for(int i = 0; i<size1; i++)
        {
            a[i]=sc1.nextInt();
        }
        System.out.println("Your 1st array is:");
        for(int i = 0; i<size1; i++)
        {
            System.out.print(a[i] + " ");
        }
        System.out.println("Enter the values in 2nd array:");
        for(int j = 0; j<size2; j++)
        {
            b[j]=sc2.nextInt();
        }
        System.out.println("Your 2nd array is:");
        for(int j = 0; j<size2; j++)
        {
            System.out.print(b[j] + " ");
        }
        for(int k=0,i=0,j=0; k<(size1+size2);)
        {
            if(k<size1)
            {
                c[k]=a[i];
                k++;i++;
            }
            else
            {
                c[k]=b[j];
                k++;j++;
            }
        }
        System.out.println("Your 3rd array is:");
        for(int k = 0; k<(size1+size2); k++)
        {
            System.out.print(c[k] + " ");
        }
    }
}

Output:-

Merge array index wise search output


Post a Comment

0 Comments