Você está na página 1de 3

Question:

Write a Program in Java 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.
For example: If rows = 4 and columns = 5, then the result should be:

Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* The class Fill_Prime fills a 2D array with 'r*c' Prime numbers
* @author : www.javaforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.io.*;
class Fill_Prime
{

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;
}

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public static void main(String args[])throws IOException
{
Fill_Prime ob = new Fill_Prime();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

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

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

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

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

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

/* Printing the resultant 2D array */
System.out.println("The Filled Array is :");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
68
69
70
71
72
73
74
{
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.


Source: http://www.javaforschool.com/1705172-java-program-to-fill-a-2-d-array-with-prime-
numbers/#ixzz3CbQdrmbH

Você também pode gostar