A class Composite contains a two-dimensional array of order [m x n]. The maximum values possible for both ‘m’ and ‘n’ is 20. Design a class Composite to fill the array with the first (m x n) composite numbers in column wise. [Composite numbers are those which have more than two factors.]The details of the members of the class are given below:
Class name: Composite
Data members/instance variables :arr[ ] [ ] :integer array to store the composite numbers column wise
m :integer to store the number of rows
n:integer to store the number of columns
Member functions/methods:
Composite(int mm, int nn ):to initialize the size of the matrix, m=mm and n=nn
int isComposite( int p ):to return 1 if the number is composite otherwise returns 0
void fill ( ):to fill the elements of the array with the first (m × n) composite numbers in column wise
void display( ):to display the array in a matrix form Specify the class Composite giving details of the constructor(int,int), int isComposite(int), void fill( ) and void display( ). Define a main( ) function to create an object and call all the functions accordingly to enable the task.
class Composite
{
int m,n,arr[][];
Scanner sc=new Scanner(System.in);
Composite(int mm, int nn)
{
m=mm;
n=nn;
arr=new int [m][n];
}
private int isComposite( int p )
{
int i;
for(i=2;i<p;i++)
{
if(p%i==0)
break;
}
if(i==p)
return 0;
else
return 1;
}
private void display()
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print(" "+arr[i][j]);
}
System.out.println();
}
}
void fill ( )
{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print("\nEnter Number:");
int d=sc.nextInt();
if(isComposite(d)==1)
arr[i][j]=d;
else
{
System.out.print("\nEnter Composite Number "+d + " is not composite");
j--;
}
}
}
}
public static void main(String args[])
{
int m,n;
Scanner sc=new Scanner(System.in);
while(true)
{
System.out.print("\nEnter Row Number:");
m=sc.nextInt();
if(m>0 && m<=20)
break;
}
while(true)
{
System.out.print("\nEnter Column Number:");
n=sc.nextInt();
if(n>0 && n<=20)
break;
}
Composite ob=new Composite(m,n);
ob.fill();
System.out.print("\nFinal Matrix\n");
ob.display();
}
}
No comments:
Post a Comment