prime fill

Upload: atharvashukla

Post on 02-Jun-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 Prime Fill

    1/3

    Question:

    Write a Program in Java to fill a 2- D array with the first r*c prime numbers, where r is the numberof rows and c is the number of columns.

    For example: If rows = 4 and columns = 5, then the result should be:

    Solution:

    123456

    78910111213141516

    1718192021222324

    /** * 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

  • 8/10/2019 Prime Fill

    2/3

    252627282930313233343536373839

    40414243444546474849

    50515253545556575859

    6061626364656667

    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

  • 8/10/2019 Prime Fill

    3/3

    68697071727374

    { 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 andreplace 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 theabove program with the appropriate function.

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

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