Thursday, December 8, 2022

BlueJ Program On Merging Two Arrays With Odd Elements Followed By Even Elements

 Design a class OddEven to arrange two single dimensional arrays into one single dimensional array, such that the odd numbers from both the arrays are at the beginning followed by the even numbers. 

Example: Array 1: { 2, 13, 6, 19, 26, 11, 4 }

 Array 2: { 7, 22, 4, 17, 12, 45 } 

 Arranged Array = { 13, 19 11, 7, 17, 45, 2, 6, 26, 4, 22, 4, 12 } 


Some of the members of the class are given below: 

Class name : OddEven 

Data members/instance variables: 

a[ ] : to store integers in the array

 m : integer to store the size of the array 

Methods / Member functions: 

OddEven(int mm) : parameterised constructor to initialize the data member m=mm 

void fillarray( ) : to enter integer elements in the array 

OddEven arrange(OddEven P, OddEven Q ) : stores the odd numbers from both the parameterized object arrays followed by the even numbers from both the arrays and returns the object with the arranged array 

void display( ) : displays the elements of the arranged array 

Specify the class OddEven giving details of the constructor( ), void fillarray( ), OddEven arrange(OddEven, OddEven) and void display( ). Define a main( ) function to create objects and call the functions accordingly to enable the task.


Program


import java.io.*;
public class Arrange
{
int a[],m;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Arrange(int mm)
{
     m=mm;
     a=new int [m];
}
private void fillArray()throws IOException
{
    for(int i=0;i<m;i++)
    {
        System.out.print("\nValue: ");
        a[i]=Integer.parseInt(br.readLine());
    }
}
private Main arrange(Main P, Main Q)
{
    int x=0;
    Main obj=new Main(P.m+Q.m);
    for(int i=0;i<P.m;i++)
    {
        if(P.a[i]%2!=0)
        obj.a[x++]=P.a[i];
    } 
     for(int i=0;i<Q.m;i++)
    {
        if(Q.a[i]%2!=0)
        obj.a[x++]=Q.a[i];
    } 
    
    for(int i=0;i<P.m;i++)
    {
        if(P.a[i]%2==0)
        obj.a[x++]=P.a[i];
    } 
     for(int i=0;i<Q.m;i++)
    {
        if(Q.a[i]%2==0)
        obj.a[x++]=Q.a[i];
    } 
    return obj;
    
    }
private void display()
{
    for(int i=0;i<m;i++)
    System.out.print(" "+a[i]);
}
     public static void main(String[] args) throws IOException
     {
        Arrange P,Q,ob;
         P=new Arrange(6);
         Q=new Arrange(4);
         ob=new Arrange(1);
          System.out.println("\n1st Array");
         P.fillArray();
          System.out.println("\n2nd Array");
         Q.fillArray();
         ob=ob.arrange(P,Q);
         
System.out.println("\n1st Array");
P.display();
System.out.println("\n2nd Array");
Q.display();
System.out.println("\nFinal Array");
ob.display();
}
}


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner