Monday , 15 October 2018
Latest Posts
Home » Array Related Programs » Java program to fill a 2-D array with Prime numbers

# Java program to fill a 2-D array with Prime numbers

#### Question:

Write a Program in Java to fill a 2-D array with the first ‘m*n’ prime numbers, where ‘m’ is the number of rows and ‘n’ is the number of columns.

For example: If rows = 4 and columns = 5, then the result should be:

#### Solution:

```/**
* The class FillPrime fills a 2D array with 'm*n' Prime numbers
* @author : www.javaforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.io.*;
class FillPrime
{

boolean isPrime(int n) // Function for checking whether a number is prime or not
{
int c = 0;
for(int i = 1; i<=n; i++)
{
if(n%i == 0)
c++;
}
if(c == 2)
return true;
else
return false;
}

public static void main(String args[])throws IOException
{
FillPrime ob = new FillPrime();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the number of rows: ");
int m=Integer.parseInt(br.readLine());
System.out.print("Enter the number of columns: ");
int n=Integer.parseInt(br.readLine());

int A[][]=new int[m][n]; // 2D array for storing 'm*n' prime numbers
int B[] = new int [m*n]; // 1D array for storing 'm*n' prime numbers

int i = 0, j;
int k = 1; // For generating natural numbers

/* First saving the 'm*n' prime numbers into a 1D Array */
while(i < m*n)
{
if(ob.isPrime(k)==true)
{
B[i] = k;
i++;
}
k++;
}

/* Saving the 'm*n' prime numbers from 1D array into the 2D Array */
int x = 0;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
A[i][j] = B[x];
x++;
}
}

/* Printing the resultant 2D array */
System.out.println("The Filled Array is :");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}
}
}```

Note: If you are asked to input a square matrix of size ‘n*n’ then just input the value of ‘n’ and replace ‘r’ and ‘c’ in the above program with ‘n’.
Similarly, you can fill a 2D array with any type of number. Just replace the function isPrime() in the above program with the appropriate function.

## ISC 2017 Computer Science Solution + Examiner’s Comments – From the Council

Solution of ISC 2017 Computer science Paper as provided by the Council for the Indian School Certificate Examinations.