Go to Top

Tuesday, 4 October 2011

To generate a sample matrix

Question 55 : Write a program in Java to generate a sample matrix based upon the number of rows and columns taken as input from the user.

Sample input : Rows = 2 ; Columns = 2

Sample output : 

[ 1 2 
  3 4 ]

Java Program :

import java.io.*;
class matrix
{
 int[] a;
 static int opt=0;
 static void main()throws IOException
 {
     order();
    }
    static void order()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        if(opt==0)
        {
            System.out.print("Enter number of rows : ");
            int r=Integer.parseInt(br.readLine());
            System.out.print("\nEnter number of columns : ");
            int c=Integer.parseInt(br.readLine());
            System.out.print("\n=> Order of matrix : "+r+" X "+c);
            System.out.print("\n\nSample matrix : \n\n");
            System.out.print("[ ");
            int c1=0;
            for(int i=1;i<=(r*c);i++)
            {
                if(c1==c)
                {
                    System.out.print("\n  ");
                    c1=0;
                }
                c1++;
                System.out.print(i+" ");
            }
            System.out.print("]");
        }
    }
}
        

No comments:

Post a Comment

ShareThis