Fill Matrix with Composite Numbers

A class Composite contains a two-dimensional array of order [m × n]. The maximum value possible for both ‘m’ and ‘n’ is 20. Design a class Composite to fill the array with the first (m × n) composite numbers in column-wise. The details of the members of the class are given below:

Class name: Composite
Data members/instance variables:
arr[][]: stores 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 r, int c): to initialize the size of the matrix m = r and n = c.
int isComposite(int p): returns 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(): displays the array in a matrix form.

Specify the class Composite giving details of the constructor, int isComposite(int), void fill() and void display(). Define a main() function to create an object and call the functions accordingly to enable the task.

import java.io.*;
class Composite{
    int arr[][];
    int m;
    int n;
    public Composite(int r, int c){
        m = r;
        n = c;
        arr = new int[m][n];
    }
    public int isComposite(int p){
        int f = 0;
        for(int i = 1; i <= p; i++) 
            if(p % i == 0) 
                f++; 
        if(f > 2)
            return 1;
        return 0;
    }
    public void fill(){
        int t = 4;
        int result = 0;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                while((isComposite(t)) != 1)
                    t++;
                arr[j][i] = t;
                t++;
            }
        }
    }
    public void display(){
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++) 
                System.out.print(arr[i][j] + "\t"); 
            System.out.println(); 
        } 
    } 
    public static void main(String args[])throws IOException{ 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
        System.out.print("Number of rows: "); 
        int rows = Integer.parseInt(br.readLine()); 
        System.out.print("Number of columns: "); 
        int columns = Integer.parseInt(br.readLine()); 
        if(rows > 20 || columns > 20){
            System.out.println("Size out of range!");
            return;
        }
        Composite obj = new Composite(rows, columns);
        obj.fill();
        obj.display();
    }
}

4 thoughts on “Fill Matrix with Composite Numbers

  1. Sir,in the question of filling the Matrix with composite numbers is told to fill column wise not row wise. Please update the program as soon as possible.

  2. Sir,what is the meaning of filling a Matrix with prime numbers in column wise in java?Can you show a sample output of 4×3 Matrix

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.