» » add two matrices

  1. package com.instanceofjava;
  2.  
  3. import java.util.Scanner;
  4.  
  5. class Add2Matrix
  6. {
  7.  
  8.    public static void main(String args[])
  9.    {
  10.  
  11.       int rows, cols, c, d;
  12.  
  13.       Scanner in = new Scanner(System.in);
  14.  
  15.       System.out.println("Please Enter number of rows and columns");
  16.  
  17.       rows = in.nextInt();
  18.       cols  = in.nextInt();
  19.  
  20.       int first[][] = new int[rows][cols];
  21.       int second[][] = new int[rows][cols];
  22.       int sum[][] = new int[rows][cols];
  23.  
  24.       System.out.println("Please Enter elements of first matrix");
  25.  
  26.       for (  c = 0 ; c < rows ; c++ )
  27.          for ( d = 0 ; d < cols ; d++ )
  28.             first[c][d] = in.nextInt();
  29.  
  30.       System.out.println("Please Enter elements of second matrix");
  31.  
  32.       for ( c = 0 ; c < rows ; c++ )
  33.          for ( d = 0 ; d < cols ; d++ )
  34.             second[c][d] = in.nextInt();
  35.  
  36.       for ( c = 0 ; c < rows ; c++ )
  37.          for ( d = 0 ; d < cols ; d++ )
  38.              sum[c][d] = first[c][d] + second[c][d];  //replace '+' with '-' to subtract matrices
  39.  
  40.       System.out.println("Sum of entered matrices:-");
  41.  
  42.       for ( c = 0 ; c < rows ; c++ )
  43.       {
  44.          for ( d = 0 ; d < cols ; d++ )
  45.             System.out.print(sum[c][d]+"\t");
  46.          System.out.println();
  47.       }
  48.    }

  49.  }
  50.    
     

 

Output:

  1. Please Enter number of rows and columns
  2.  
  3. 3
  4. 3
  5.  
  6. Please Enter elements of first matrix
  7.  
  8. 1 1 1
  9. 1 1 1
  10. 1 1 1
  11.  
  12. Please Enter elements of second matrix
  13.  
  14. 2 2 2
  15. 2 2 2
  16. 2 2 2
  17.  
  18. Sum of entered matrices:-
  19.  
  20. 3    3    3    
  21. 3    3    3    
  22. 3    3    3  

You might like:



Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu