Wednesday, January 28, 2015

Java program to print out a matrix

The java program given below will print a matrix after getting the data from the users. When you will run this program, then you will be asked to provide the number of rows of the matrix and later you will be asked to provide the number of columns.

Then you have to provide the data of the matrix one by one. If you want to display a matrix of 2 rows and 2 columns, then you have to provide (2*2) 4 data. The first two data will be for the first row and the next two data will be for the second row.

A double array is used to store several data for the matrix. Not only declaring a double array, we also need to use a for loop inside another for loop to store data in the double array. Similarly, we need to use another set of for loop to display the matrix.
java program,matrix in java
import java.util.*;

public class Matrix{
 public static void main(String [] args){
  //creating scanner object
  Scanner in = new Scanner(System.in);
  
  //showing message to enter the number of rows
  System.out.print("Enter the number of rows: ");
  int rows = in.nextInt();

  //showing message to enter the number of columns
  System.out.print("Enter the number of columns: ");
  int columns = in.nextInt();
  
  //declaring a double array array
  int matrix[][] = new int[30][30];

  //getting input
  System.out.println("\n\nEnter the data...");
  for(int i=1; i<=rows; i++){
   for(int j=1; j<=columns; j++){
    matrix[i][j] = in.nextInt();
   }
  }

  //showing the matrix
  System.out.println("\n\nThe matrix is...");
  for(int i=1; i<=rows; i++){
   for(int j=1; j<=columns; j++){
    System.out.print(matrix[i][j]+"  ");
   } System.out.print("\n\n");
  }
 }
}


No comments:

Post a Comment