How to print an array with prime numbers in java?

The blog provides the technical approach on ” How to print an array with prime numbers in java? “

Problem Statement: 

How to print an One Dimensional or Two Dimensional array with prime numbers in java?

package com.java.planforexams.array;
import java.io.IOException;
import java.util.Scanner;
public class ArrayWithPrimeNumbers {
		public static void main(String args[])throws IOException
		{
			// create object of Prime number matrix.
			ArrayWithPrimeNumbers ob = new ArrayWithPrimeNumbers();
			// Scanner object for reading User Input
			Scanner scan = new Scanner(System.in);
			// Enter Row Count
			System.out.print("Enter the number of rows : ");
			int m= scan.nextInt();
			// Enter Column count
			System.out.print("Enter the number of columns : ");
			int n= scan.nextInt();
			// 2D array for storing 'm*n' prime numbers
			int TwoDimensionalWithPrimeNumbers[][]=new int[m][n];
			// 1D array for storing 'm*n' prime numbers
			int OneDimensionalWithPrimeNumbers[] = new int [m*n];
			
			int i = 0, j;
			int k = 1; 
			// for iD Array.
			while(i < m*n)
			{
				if(ob.isPrime(k)==true)
				{
					OneDimensionalWithPrimeNumbers[i] = k;
					i++;
				}
				k++;
			}
			// Two Dimensional Array.
			int x = 0;
			for(int innerIncr=0; innerIncr<m; innerIncr++)
			{
				for(int outerIncr=0; outerIncr<n; outerIncr++)
				{
					TwoDimensionalWithPrimeNumbers[innerIncr][outerIncr] = 
                      OneDimensionalWithPrimeNumbers[x];
					x++;
				}
			}

			// Print the Two Dimensional Array with Prime Numbers
			System.out.println("Two Dimensional Array with Prime Numbers is : ");
			for(int innerIncr=0; innerIncr<m; innerIncr++)
			{
				for(int outerIncr=0; outerIncr<n; outerIncr++)
				{
					System.out.print(TwoDimensionalWithPrimeNumbers[innerIncr]
                                     [outerIncr]+"\t");
				}
			}
		}
		// Function to check a number is prime or not
		boolean isPrime(int n) 
		{
			int c = 0;
			for(int i = 1; i<=n; i++)
			{
				if(n%i == 0)
					c++;
			}
			if(c == 2)
				return true;
			else
				return false;
		}
	}

Leave a Reply

Your email address will not be published. Required fields are marked *

*