Java program to fill a 2-D array with Prime numbers
Java program to fill a 2-D array with the first 'r*c' prime numbers, where 'r' is the number of rows and 'c' is the number of columns.
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:
Java
/**
* The class FillPrime fills a 2D array with 'm*n' Prime numbers
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/
import java.util.Scanner;
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[])
{
FillPrime ob = new FillPrime();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int m=sc.nextInt();
System.out.print("Enter the number of columns: ");
int n=sc.nextInt();
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.

