KnowledgeBoat Logo

Computer Science

Write a Program in Java to fill a 2D array with the first 'mxn' 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:

235711
1317192329
3137414347
5359616771

Java

Java Arrays

17 Likes

Answer

import java.util.Scanner;

public class KboatSDAPrime
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number of rows (m): ");
        int m = in.nextInt();
        System.out.print("Enter number of columns (n): ");
        int n = in.nextInt();

        int arr[][] = new int[m][n];
        int r = 0, c = 0;
        int total = m * n;
        int count = 0;
        for (int i = 2; count < total; i++) {
            
            int div = 0;
            for (int j = 1; j <= i; j++) {
                if (i % j == 0) {
                    div++;
                }
            }

            if (div == 2) {
                arr[r][c++] = i;
                count++;
                if (c == n) {
                    r++;
                    c = 0;
                }
            }

        }
        
        System.out.println("Prime Numbers Array:");
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

Output

BlueJ output of Write a Program in Java to fill a 2D array with the first 'mxn' 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:

Answered By

4 Likes


Related Questions