SUNDAY, 12 JULY 2026
Guide For School logo Guide For SchoolStudy Guide For Students On Java Programming
Physics | Chemistry | Mathematics
ICSE | ISC | CBSE
Guide For School logo Guide For SchoolICSE and ISC Resources

Prime Numbers in 2D Array Program in Java and Python

19 February 2014

Prime numbers in 2D array program with algorithm, explanation, Java solution and simple Python solution for ICSE and ISC students.

Question:

Write a program to input the number of rows and columns of a 2-D array and fill it with the first rows × columns prime numbers.

INPUT: Enter the number of rows: 3 Enter the number of columns: 4 OUTPUT: Prime number matrix: 2 3 5 7 11 13 17 19 23 29 31 37

Algorithm:

Step 1: Start.

Step 2: Accept the number of rows m and columns n.

Step 3: Declare matrix A[m][n].

Step 4: Initialize num to 2, the first prime number candidate.

Step 5: For each matrix cell A[i][j], test num using the isPrime method.

Step 6: While num is not prime, increment num.

Step 7: Store the prime value of num in A[i][j].

Step 8: Increment num so the next search starts from the following number.

Step 9: After all cells are filled, display the matrix.

Step 10: Stop.

Explanation:

The program fills a matrix with consecutive prime numbers, starting from 2. The number of primes required is equal to rows × columns, because every matrix cell must receive one value.

The method isPrime() checks whether a number has exactly two factors. It counts all numbers from 1 to n that divide n fully. If the count is 2, the number is prime.

The variable num stores the current number being tested. For each matrix position, the program keeps increasing num until isPrime(num) returns true. That prime number is then stored in the current cell.

After storing a prime number, num is increased so the next search begins from the following number. This ensures the matrix contains prime numbers in increasing order without repetition.

The central idea is to generate valid prime numbers before placing them in the matrix. The program cannot simply fill the array with consecutive numbers, because only numbers with exactly two factors are allowed. A prime-checking routine is therefore used while searching through integers. Whenever a prime number is found, it is inserted into the current matrix position. The row and column loops control placement, while the prime test controls which values are accepted. This separation keeps the matrix-filling logic clear and prevents non-prime values from entering the array.

Java Program:

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

Equivalent Python Program:

Python
# Read the matrix or array size and store the values for indexed processing.
# Helper functions keep repeated calculations separate from the main logic.
# Nested loops are used because each row/column or array position must be checked.
# Print the processed array or matrix in the required output format.

def is_prime(n):
    count = 0
    for i in range(1, n + 1):
        if n % i == 0:
            count = count + 1
    return count == 2

m = int(input("Enter the number of rows: "))
n = int(input("Enter the number of columns: "))

A = []
num = 2
for i in range(m):
    row = []
    for j in range(n):
        while is_prime(num) == False:
            num = num + 1
        row.append(num)
        num = num + 1
    A.append(row)

print("Prime number matrix:")
for i in range(m):
    for j in range(n):
        print(A[i][j], end="	")
    print()

Output:

INPUT: Enter the number of rows: 3 Enter the number of columns: 4 OUTPUT: Prime number matrix: 2 3 5 7 11 13 17 19 23 29 31 37

Leave a Reply

Your email address will not be published. Comments are reviewed before appearing publicly.

Send a comment or correction

Study smarter

Everything you need for ICSE and ISC Computer

Programs, revision notes, solved papers and practical guidance—organized for quick study.

Browse all resources →